http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1586
Sunny Cup 2003 - Preliminary RoundApril 20th, 12:00 - 17:00 Problem E: QS Network
A sample is shown below:
Each QS has its favorate brand of network adapters and always buys the brand in all of its connections. Also the distance between QS vary. Given the price of each QS's favorate brand of network adapters and the price of cable between each pair of QS, your task is to write a program to determine the minimum cost to setup a QS network.
The 1st line of the input contains an integer t which indicates the number of data sets. Constrains: all the integers in the input are non-negative and not more than 1000.
for each data set,output the minimum cost in a line. NO extra empty lines needed.
1
370 |
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#define maxn 10002
#define ll long long
using namespace std;
struct point
{
ll s;
} points[1050];
struct node
{
ll u;
ll v;
ll w;
} edge[1000006];
ll pre[1006];
ll n,m;
ll j;
bool cmp(const node&a,const node&b )
{
return a.w<b.w;
}
ll find(ll x)
{
return x==pre[x]?x:pre[x]=find(pre[x]);
}
void unions(ll x,ll y)
{
ll fx=find(x);
ll fy=find(y);
if(fx!=fy)
{
pre[fx]=fy;
}
}
void createGraph()
{
scanf("%lld",&n);
for(ll i=1; i<=n+10; i++)pre[i]=i;
j=0;
for(ll i=1; i<=n; i++)
{
scanf("%lld",&points[i]);
}
for(ll i=1; i<=n; i++)
{
for(ll k=1; k<=n; k++)
{
ll s;
scanf("%lld",&s);
if(i==k)continue;
j++;
edge[j].u=i;
edge[j].v=k;
edge[j].w=s+points[i].s+points[k].s;
}
}
}
ll kruscal()
{
ll ans=0;
sort( edge+1, edge+j+1,cmp);
ll cnt=0;
for(ll i=1; i<=j; i++)
{
if(find( edge[i].u)!=find( edge[i].v))
{
cnt++;
unions( edge[i].u, edge[i].v);
ans+= edge[i].w;
}
if(cnt==n-1)break;
}
return ans;
}
int main()
{
ll t;
scanf("%lld",&t);
while(t!=0)
{
--t;
createGraph();
printf("%lld\n",kruscal());
}
}