通信线路
★★ 输入文件:mcst.in
输出文件:
mcst.out
简单对比
时间限制:1.5 s 内存限制:128 MB
- #include <iostream>
- #include <cstdio>
- #include <cstring>
- #define maxn 1502
- #define Max 0x7f7f7f7f
- using namespace std;
- int Gra[maxn][maxn];
- int Min[maxn];
- bool Exi[maxn];
- int n ;
- int main()
- {
- freopen("mcst.in" ,"r",stdin );
- freopen("mcst.out","w",stdout);
- scanf("%d",&n);
- for (int i = 1 ; i <= n ; i ++ )
- {
- for (int j = 1 ; j <= n ; j ++ )
- {
- int t ;
- scanf("%d",&t);
- if (t != -1) Gra[i][j] = t ;
- else Gra[i][j] = Max ;
- }
- }
- memset(Exi,0,sizeof(Exi));
- memset(Min,0x7f,sizeof(Min));
- Min[1] = 0;
- for (int i = 1 ; i <= n ; i ++ )
- {
- int k = 0 ;
- for (int j = 1 ; j <= n ; j ++ )
- {
- if (!Exi[j] && (Min[j] < Min[k])) k = j ;
- }
- Exi[k] = true ;
- for (int j = 1 ; j <= n ; j ++ )
- {
- if (!Exi[j] && (Gra[k][j] < Min[j])) Min[j] = Gra[k][j] ;
- }
- }
- int tot = 0 ;
- for (int i = 1 ; i <= n ; i ++ ) tot += Min[i] ;
- printf("%d\n",tot) ;
- return 0;
- }
第一行,一个整数n,表示共有n个城市
第2--n+1行,每行n个数,分别表示该城市与其它城市之间路线的费用,如果城市间不能建立通信则用-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
对于60%的数据,保证有n<256;
对于全部的数据,保证有n<=1501。
Kruskal
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
using namespace std;
struct node
{
int x, y, dis;
}p[3000000];
int Find[15550];
int cmp(const void *a,const void *b)
{
struct node *c=(struct node *)a;
struct node *d=(struct node *)b;
return c->dis-d->dis;
}
int f(int x)
{
return x==Find[x]?x:Find[x]=f(Find[x]);
}
int main()
{
freopen("mcst.in","r",stdin);
freopen("mcst.out","w",stdout);
int n, a, k=0;
scanf("%d", &n);
for(int i=1;i<=n;i++)
{
Find[i]=i;
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
scanf("%d", &a);
if(j<=i||a==-1)
{
continue;
}
p[k].x=i,p[k].y=j;
p[k++].dis=a;
}
}
qsort(p,k,sizeof(p[0]),cmp);
int ans=0;
for(int i=0;i<k;i++)
{
int x=f(p[i].x),y=f(p[i].y);
if(x!=y)
{
ans+=p[i].dis;
Find[y]=x;
}
}
printf("%d\n",ans);
return 0;
}
prim