POJ 1861 Network
Time Limit: 1000MS | Memory Limit: 30000K | |||
Total Submissions: 10104 | Accepted: 3796 | Special Judge |
Description
Since cables of different types are available and shorter ones are cheaper, it is necessary to make such a plan of hub connection, that the maximum length of a single cable is minimal. There is another problem — not each hub can be connected to any other one because of compatibility problems and building geometry limitations. Of course, Andrew will provide you all necessary information about possible hub connections.
You are to help Andrew to find the way to connect hubs so that all above conditions are satisfied.
Input
Output
Sample Input
4 6 1 2 1 1 3 1 1 4 2 2 3 1 3 4 1 2 4 1
Sample Output
1 4 1 2 1 3 2 3 3 4
Source
#include <iostream>
#include <stdio.h>
#include <string.h>
#define M 150003
#define N 1003
#include <algorithm>
using namespace std;
struct node
{
int u,v,cost;
};
node kr[M];
bool cmp(const node&a,const node&b)
{
return a.cost<b.cost;
}
int n,m;
int f[N],r[N];
int Find(int x)
{
if(x!=f[x])
return f[x]=Find(f[x]);
return x;
}
int E[N];
void kruskal()
{
int i;
int Max,k;
for(i=1;i<=n;i++)
f[i]=i,r[i]=0;
sort(kr,kr+m,cmp);
Max=k=0;
int x,y;
for(i=0;i<m;i++)
{
x=Find(kr[i].u);
y=Find(kr[i].v);
if(x!=y)
{
E[k++]=i;
if(kr[i].cost>Max)
Max=kr[i].cost;
if(r[x]>r[y])
f[y]=x;
else if(r[y]>r[x])
f[x]=y;
else
{
f[y]=x;
r[x]++;
}
}
}
printf("%d\n",Max);
printf("%d\n",k);
for(int j=0;j<k;j++)
printf("%d %d\n",kr[E[j]].u,kr[E[j]].v);
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=0;i<m;i++)
scanf("%d%d%d",&kr[i].u,&kr[i].v,&kr[i].cost);
kruskal();
}
return 0;
}