1170: Wire Is So Expensive
| Result | TIME Limit | MEMORY Limit | Run Times | AC Times | JUDGE |
|---|---|---|---|---|---|
| 3s | 8192K | 620 | 259 | Standard |
1st Jilin University ACM International Collegiate Programming Contest
Assume you are working for ACM(Andrew Communication Management) company. This company is specialized to make towns connected by wire. We all know that wire can only be put along roads. But in recent years, the price of per metre of wire is going higher and higher. So the company needs to know what is the minimal length of wire they have to prepare to connect several towns together in order that each town can connect to another by wire. You are given a map of N towns and how they are connected by roads. Your task is to write a program to determine the minimal length of wire.
Input Specification
This problem contains M maps. The first line of input is an integer M. Then follow M maps' descriptions, each of which is described below:
N
a1 b1 c1
a2 b2 c2
...
an bn cn
0 0 0
where N(1<=N<=20) is the number of towns(1, 2, ... N) and ai, bi, ci means there is a road between towns ai and bi(1<=ai, bi<=N) with length ci(1<=ci<=100). Three 0s mark the end of a map. All the numbers will be integers.
Output Specification
For each map, you should print a line containing the minimal length of wire the company has to prepare.
Sample Input
1 5 1 2 3 1 4 5 2 3 6 2 4 2 2 5 6 3 5 5 4 5 8 0 0 0
Sample Output
16
#include<stdio.h>
#include<string.h>
int inf=(1<<31)-2;
int main()
{
int c[101][101];
int ll;
scanf("%d",&ll);
while(ll--)
{
int n,i,j;
scanf("%d",&n);
int ai,bi,ci;
memset(c,12,sizeof(c));
while(1)
{
scanf("%d%d%d",&ai,&bi,&ci);
if(ai==0&&bi==0&&ci==0) break;
if(ci<c[ai-1][bi-1]) c[ai-1][bi-1]=c[bi-1][ai-1]=ci;
}
int vis[100],lowc[100];
memset(vis,0,sizeof(vis));
int minc,res=0;
int p=0;
vis[0]=1;
for(i=0;i<n;i++) lowc[i]=c[0][i];
for(j=1;j<n;j++)
{
minc=inf;p=0;
for(i=0;i<n;i++)
{
if(vis[i]==0&&minc>lowc[i])
{
minc=lowc[i];
p=i;
}
}
if(minc==inf) break;
vis[p]=1;res+=minc;
for(i=0;i<n;i++)
{
if(vis[i]==0&&lowc[i]>c[p][i]) lowc[i]=c[p][i];
}
}
printf("%d/n",res);
}
return 0;
}
本文介绍了一种用于计算连接多个城镇所需的最小电线长度的算法。背景是一家专门通过电线连接城镇的公司面临着电线价格日益上涨的问题,需要计算最少的电线长度来实现城镇间的有效连接。
626

被折叠的 条评论
为什么被折叠?



