listTLE 65分
查看原帖
listTLE 65分
717599
dengjunhaodejia09楼主2022/12/30 12:26
#include <bits/stdc++.h>
using namespace std;
inline int read(){
     int x=0,f=1;
     char ch=getchar();
     while(ch<'0'||ch>'9'){
         if(ch=='-')
             f=-1;
         ch=getchar();
     }
     while(ch>='0'&&ch<='9'){
         x=(x<<1)+(x<<3)+(ch^48);
         ch=getchar();
     }
     return x*f;
 }
 inline void write(int x)
 {
     char F[200];
     int tmp=x>0?x:-x ;
     if(x<0)putchar('-') ;
     int cnt=0 ;
        while(tmp>0)
        {
            F[cnt++]=tmp%10+'0';
            tmp/=10;
        }
        while(cnt>0)putchar(F[--cnt]) ;
 }
struct node{
	int x,y,z;
};
list <node> b;
list<node> a;
int bbb[1000010];
int f[1000010];
int cmp(node a1,node b1){
	return a1.z<b1.z;
}
int find(int lll){
	if(f[lll]==lll){
		return lll;
	}
	f[lll]=find(f[lll]);
	return f[lll];
}
void hebing(int a1,int b1){
	int eee=find(a1),eeee=find(b1);
	if(eee==eeee){
		return;
	}else{
		f[eee]=eeee;
	}
}
int main(){
	int n,m;
	n=read();
	m=read();
	for(int i=1;i<=m;i++){
		node f;
		f.x=read();
		f.y=read();
		f.z=read();
		b.push_back(f);
	}
	bool k=false;
	
	for(int i1=m;i1>=1;i1--){
		if(k==true){
			bbb[i1]=-1;	
			continue;
		}
		a=b;
		a.sort(cmp);
		list<node>::iterator i=a.begin();
		for(int i=1;i<=n;i++){
			f[i]=i;
		}
		int ans=0,o=0,p=0;
		while(i!=a.end()){
			int ee=find((*i).x),eee=find((*i).y);
			if(ee==eee){
				++i;
				continue;
			}
			ans+=(*i).z;
			o++;
			hebing((*i).x,(*i).y);
			if(o==n-1){
				break;
			}
			++i;
		}
		if(o==n-1){
			bbb[i1]=ans;
		}else{
			bbb[i1]=-1;
			k=true;
		}
		b.pop_back();
	}
	for(int i=1;i<=m;i++){
		write(bbb[i]);
		printf("\n");
	}
	return 0;
}
2022/12/30 12:26
加载中...