cogs 7. 通信线路
★★ 输入文件:mcst.in 输出文件:mcst.out 简单对比
时间限制:1.5 s 内存限制:128 MB
问题描述
假设要在n个城市之间建立通信联络网,则连通n个城市只需要n-1条线路。这时, 如何在最少经费的前提下建立这个通信网。在每两个城市之间都可以设置—条线路,相应地都要付出一定的经济代价。n个城市之间,最多可能设置n(n- 1)/2条线路,那么,如何在这些可能的线路中选择n-1条,以使总的耗费最少呢?
【输入格式】
输入文件有若干行
第一行,一个整数n,表示共有n个城市
第2--n+1行,每行n个数,分别表示该城市与其它城市之间路线的费用,如果城市间不能建立通信则用-1表示
第一行,一个整数n,表示共有n个城市
第2--n+1行,每行n个数,分别表示该城市与其它城市之间路线的费用,如果城市间不能建立通信则用-1表示
【输出格式】
一行,1个整数,表示最少总费用
【输入输出样例】
输入文件
6
-1 5 -1 -1 -1 -1
5 -1 50 -1 -1 10
-1 50 -1 20 10 -1
-1 -1 20 -1 60 30
-1 -1 10 60 -1 100
-1 10 -1 30 100 -1
-1 5 -1 -1 -1 -1
5 -1 50 -1 -1 10
-1 50 -1 20 10 -1
-1 -1 20 -1 60 30
-1 -1 10 60 -1 100
-1 10 -1 30 100 -1
输出文件
75
【数据规模】
对于40%的数据,保证有n<100:
对于60%的数据,保证有n<256;
对于全部的数据,保证有n<=1501。
对于60%的数据,保证有n<256;
对于全部的数据,保证有n<=1501。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
const int N=3000100;
int fa[N>>2],w,js,answer,tot,n;
struct node{
int x,y,dis;
}E[N];
inline int read()
{
int x=0;int f=1;char c=getchar();
while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
while(c>='0'&&c<='9')x=x*10+c-'0',c=getchar();
return x*f;
}
inline bool cmp(node a,node b)
{
return a.dis<b.dis;
}
int getfa(int x)
{
return fa[x]==x?x:fa[x]=getfa(fa[x]);
}
int main()
{
freopen("mcst.in","r",stdin);
freopen("mcst.out","w",stdout);
n=read();
for(int i=1;i<=n;i++)
fa[i]=i;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
w=read();
if(w!=-1&&j>i)
E[++js].x=i,
E[js].y=j,
E[js].dis=w;
}
sort(E+1,E+js+1,cmp);
for(int i=1;i<=js;i++)
{
int fx=getfa(E[i].x);
int fy=getfa(E[i].y);
if(fx!=fy)
{
tot++;
fa[fx]=fy;
answer+=E[i].dis;
if(tot==n-1)
break;
}
}
printf("%d",answer);
return 0;
}

浙公网安备 33010602011771号