求助大佬,prim和kruskal都WA qaq
查看原帖
求助大佬,prim和kruskal都WA qaq
265037
UntilR楼主2020/7/9 17:48

rt

// # prim #
#include <bits/stdc++.h>
using namespace std;
#define pa pair<int,int>
priority_queue<pa,vector<pa>,greater<pa> > line;
struct side
{
	int dot,weight,next;
}a[400001];
int s[5001],f[5001],n,m,k,top,g[5001];
bool d[5001];
long long z;
void mem(int q,int w,int e)
{
	a[++top].dot=w;
	a[top].weight=e;
	a[top].next=s[q];
	s[q]=top;
	return;
}
int main()
{
	cin>>n>>m;
	for(int i=1;i<=n;i++)
		f[i]=1e9;
	for(int i=1;i<=m;i++)
	{
		int q,w,e;
		cin>>q>>w>>e;
		mem(q,w,e);
		mem(w,q,e);
	}
	f[1]=0;
	pa o(0,1);
	line.push(o);
	while(!line.empty())
	{
		int q=line.top().second;
		line.pop();
		if(d[q]==1)
			continue;
		k++;
		d[q]=1;
		int w=s[q];
		while(w)
		{
			if(f[a[w].dot]>f[q]+a[w].weight)
			{
				f[a[w].dot]=f[q]+a[w].weight;
				g[a[w].dot]=q;
				pa r(f[a[w].dot],a[w].dot);
				line.push(r);
			}
			w=a[w].next;
		}
	}
	if(k<n-1)
	{
		cout<<"orz";
		return 0;
	}
	for(int i=1;i<=n;i++)
		z+=(f[i]-f[g[i]]);
	cout<<z;
	return 0;
}

// # kruskal #
#include <bits/stdc++.h>
using namespace std;
#define pa pair<int,int>
struct side
{
	int dot[3],weight;
}a[400001];
priority_queue<pa,vector<pa>,greater<pa> > line;
int fa[5001],n,m,k;
long long z;
int findfa(int x)
{
	if(fa[x]==x)
		return x;
	return fa[x]=findfa(fa[x]);
}
int main()
{
	cin>>n>>m;
	for(int i=1;i<=n;i++)
		fa[i]=i;
	for(int i=1;i<=m;i++)
	{
		int q,w,e;
		cin>>q>>w>>e;
		a[i].dot[1]=q;
		a[i].dot[2]=w;
		a[i].weight=e;
		pa r(e,i);
		line.push(r);
	}
	while(!line.empty()&&k<n-1)
	{
		int t=line.top().second,y=line.top().first;
		line.pop();
		if(findfa(a[t].dot[1])==findfa(a[t].dot[2]))
			continue;
		fa[a[t].dot[1]]=fa[a[t].dot[2]];
		z+=y;
		k++;
	}
	if(k<n-1)
		cout<<"orz";
	else
		cout<<z;
	return 0;
}
2020/7/9 17:48
加载中...