joj2436 Next Generation Network

2436 : Next Generation Network


ResultTIME LimitMEMORY LimitRun TimesAC TimesJUDGE
5s32768K1218158Standard

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值