为什么TLE啊N*W的算法
查看原帖
为什么TLE啊N*W的算法
102235
Mathmetastic楼主2020/12/7 09:29
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
using namespace std;
struct op{
	int from,to,val;
}d[100010];
int n,w,ans;
int f[100010];
int m[230][230];
bool b[100010];
bool cmp(op k,op kk){
	return k.val<kk.val;
}
int find(int x){
	return x==f[x]?f[x]:f[x]=find(f[x]);
}
void go(int cnt){
	int tot=0;
	memset(b,0,sizeof(b));
	ans=0;
	if(cnt<n-1){
		printf("-1\n");
		return ;
	}
	for(int i=1;i<=n;i++){
		f[i]=i;
	}
	sort(d+1,d+1+cnt,cmp);
	for(int i=1;i<=cnt-1;i++){
		if(find(d[i].from)!=find(d[i].to)){
			f[find(d[i].from)]=find(d[i].to);
			b[i]=1;
			tot++;
			ans+=d[i].val;
			if(tot==n-1)	break;
		}
	}
	if(tot==n-1){
		printf("%d\n",ans);
	}
	else printf("-1\n");
}
int main(){
	scanf("%d%d",&n,&w);
//	memset(m,0x3f,sizeof(m));
	for(int i=1;i<=w;i++){
		scanf("%d%d%d",&d[i].from,&d[i].to,&d[i].val);
		if(m[d[i].from][d[i].to]){
			if(m[d[i].from][d[i].to]<=d[i].val){
				printf("%d\n",ans);
				continue;
			}
			else{
				if(b[i]==1){
					printf("%d\n",ans+d[i].val-m[d[i].from][d[i].to]);
					continue;			
				}
			}
		}
		m[d[i].from][d[i].to]=d[i].val;
		m[d[i].to][d[i].from]=d[i].val;
		go(i);
	}
	return 0;
} 
2020/12/7 09:29
加载中...