CCF CSP 201812-4 test question Name: Data Center

Test question No.: 201812-4
Test question Name: Data Center
Time limit: 1.0s
Memory limit: 512.0MB
Problem Description:

sample input
4
5
1
1 2 3
1 3 4
1 4 5
2 3 8
3 4 2
sample output
4
Sample explanation

1. The essence of the problem is to find the maximum edge of the minimum spanning tree.
2. In the exam, the Prim algorithm was used by mistake, which was not only complex to implement, but also exceeded the time limit, and only got 50 points.
3. The correct solution is Krustkal algorithm + parallel search set, which is very simple.
4. Baidu can use its own algorithm. Some blogs have been written very clearly.

Here is the solution code.
Kruskal + parallel search set:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn=1000000;
int prt[maxn];
struct edge{
	int v;
	int u;
	int t;
}; 
bool cmp(edge const &A,const edge &B)
{
	return A.t<B.t;
}
void init(int n)
{
	for(int i=1;i<=n;++i)
		prt[i]=i;
}
int find(int x)
{
	while(prt[x]!=x)
	{
		prt[x]=prt[prt[x]];
		x=prt[x];
	}
	return x;
}
bool joint(int x,int y)
{
	int fx=find(x);
	int fy=find(y);
	if(fx==fy)
		return false;
	else
		{
			prt[fx]=fy;
			return true;
		}
}
vector<edge>E;
int main()
{
	int n,m,r;
	int cnt=0,ans=0;
	cin>>n>>m>>r;
	for(int i=0;i<m;++i)
	{
		edge Temp;
		cin>>Temp.v>>Temp.u>>Temp.t;
		E.push_back(Temp);
	}
	sort(E.begin(),E.end(),cmp);
	init(n);
	for(int i=0;i<m;++i)
	{
		if(joint(E[i].v,E[i].u))
		{
			cnt++;
			ans=E[i].t;
		}
		if(cnt==n-1)
			break;
	}
	cout<<ans;
}

Prim algorithm (time limit exceeded):

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn=500;
const long long INF=1<<30;
int visit[maxn]={false};
vector<int> vi;
struct Node{
	int id;
	long long wgt;
};
vector< vector<Node> >G(maxn);
int n;
int len=0;
int maxe=0;
void prim(int s)
{
	visit[s]=true;
	vi.push_back(s);
	for(int i=0;i<n-1;i++)
	{
		int u=-1;
		long long MIN=INF;
		for(int j=0;j<vi.size();++j)
		{
			for(int k=0;k<G[k].size();++k)
			{
				Node N=G[vi[j]][k];
				if(visit[N.id])
					continue;
				if(N.wgt<MIN)
					{
						MIN=N.wgt;
						u=N.id; 
					}
			}
		}
		if(-1==u)
			return ;
		len+=MIN;
		if(MIN>maxe)
			maxe=MIN;
		visit[u]=true;
		vi.push_back(u);
		
	 } 	
}

int main()
{
	int m,r;
	cin>>n>>m>>r;
	for(int i=0;i<m;++i)
	{
		int v,u,t;
		Node N1,N2;
		cin>>v>>u>>t;
		N1.id=u;
		N1.wgt=t;
		N2.id=v;
		N2.wgt=t;
		G[v].push_back(N1);
		G[u].push_back(N2);
	}
	prim(r);
	cout<<maxe;
}

Posted by eth0g on Wed, 04 Dec 2019 08:41:34 -0800