2436 : Next Generation Network
Result | TIME Limit | MEMORY Limit | Run Times | AC Times | JUDGE |
---|---|---|---|---|---|
![]() | 5s | 32768K | 1218 | 158 | Standard |
There are many citys in island A. In the old days, they communicate with each other using telephone. A telephone line connect two citys. There have existing some telephone lines.
The king of island A want his kingdom more modern. He prepare to construct an internet-network in his island, so every city can communicate with each other using internet-network directly or indirectly. But he is a stingy person. He only want to upgrade some existing telephone lines and cost the minimal money. Upgrade a telephone line must use half of its origin cost.
Input
The first line of each case has two integers: number of citys N(1<=N<=1000), number of existing telephone lines M(1<=M<=1000000). Following M lines each contain three integers u(1<=u<=N), v(1<=v<=N), w(0<=w<=1000). Means thers is a telephone line between city u and city v, its origin cost is w.
Output
Output the minimal upgrade cost if the king can achieve his aim. Otherwise output -1.
Sample Input
3 3
1 2 10
1 3 20
2 3 10
10 6
1 2 10
3 4 20
5 6 10
7 8 20
9 10 10
1 2 10
Sample Output
10
-1
利用深搜来判断图是否连通,若不连通,输出-1。利用Prime算法求最小生成树。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int map[1005][1005];
int lowcost[1005];
bool s[1005],f[1005];
int n,m,sum;
const int maxvalue=2000;
int prime()//求最小生成树的prime算法
{
int i,j,k,min;
int mincost=0;
s[0]=true;//将0点放入生成树的顶点集合中
for(i=1;i<n;i++)
lowcost[i]=map[0][i];//个点到生成树顶点的最短距离
for(i=0;i<n-1;i++)
{
min=maxvalue;
k=1;
for(j=1;j<n;j++)
if(!s[j]&&lowcost[j]<min)
{
min=lowcost[j];
k=j;
}
s[k]=true;
mincost+=min;
for(j=0;j<n;j++)
if(!s[j]&&map[k][j]<lowcost[j])
lowcost[j]=map[k][j];
}
return mincost;
}
void dfs(int cur)//dfs判断图是否连通
{
for(int i=0;i<n;i++)
{
if(!f[i]&&map[cur][i]!=maxvalue)
{
f[i]=true;
sum++;
dfs(i);
}
}
}
int main()
{
int i,j;
while(cin>>n>>m)
{
for(i=0;i<n;i++)
{
s[i]=false;
f[i]=false;
lowcost[i]=0;
}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
map[i][j]=maxvalue;
}
int a,b,w;
for(i=0;i<m;i++)
{
cin>>a>>b>>w;
if(w<map[a-1][b-1])
{ map[a-1][b-1]=w;
map[b-1][a-1]=w;
}
}
sum=1;
f[0]=true;
dfs(0);
//cout<<"sum: "<<sum<<endl;
if(sum==n)
{
int ans=prime();
if(ans%2==0)
{
printf("%d/n",ans/2);
}
else
{
printf("%.1lf/n",(double)ans/2);
}
}
else
printf("-1/n");
}
return 0;
}