建议加强数据
查看原帖
建议加强数据
1041101
Aventurine_stone楼主2024/6/5 20:45

单纯的桶排序求解做这道题肯定是要MLE的,但我尝试将存每个值的边的数组开小了很多,然后,过了......

#include<bits/stdc++.h>
using namespace std;
const int N=210,M=6010;
inline int read()
{
    int x=0;
    char c=getchar();
    while(c<'0'||c>'9')
        c=getchar();
    while(c>='0'&&c<='9')
        x=(x<<1)+(x<<3)+c-'0',c=getchar();
    return x;
}
int n,m,w;
typedef pair<int,int> P;
struct B{
	int x,y,z;
}a[M];
P b[10001][1010];//这里调小了一些
int len[10001];
int fa[N],size[N];
inline int find(int x)
{
	if(fa[x]==x)
		return x;
	return fa[x]=find(fa[x]);
}
int cnt,x,y,z,ans;
int main()
{
    n=read(),m=read();
    while(m--)
    {
    	w++;
    	x=read(),y=read(),z=read();
    	len[z]++;
    	b[z][len[z]]={x,y};
    	if(w<n-1)
    	{
    		printf("-1\n"); 
    		continue;
    	}
    	w=0;
    	for(int i=1;i<=10000;i++)
    		for(int j=1;j<=len[i];j++)
    			a[++w]={b[i][j].first,b[i][j].second,i};
    	for(int i=1;i<=n;i++)
    		fa[i]=i,size[i]=1;
    	cnt=0,ans=0;
    	for(int i=1;i<=w;i++)
    	{
    		x=find(a[i].x),y=find(a[i].y);
    		if(x!=y)
    		{
    			if(size[x]<size[y])
    			{
    				fa[x]=y;
    				size[x]+=size[y];
				}
				else
				{
					fa[y]=x;
					size[y]+=size[x];
				}
    			cnt++;
    			ans+=a[i].z;
			}
			if(cnt==n-1)
			{
				printf("%d\n",ans);
				break;
			}
		}
		if(cnt<n-1)
			printf("-1\n");
	}
    return 0;
}
2024/6/5 20:45
加载中...