- Authors
- Contests
- Problems
- Status
- Links
1170: Wire Is So Expensive
Result | TIME Limit | MEMORY Limit | Run Times | AC Times | JUDGE |
---|---|---|---|---|---|
![]() | 3s | 8192K | 697 | 284 | 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
Submit / Problem List / Status / Discuss
Problem Set with Online Judge System Version 3.12
Jilin University
这是一个最小支撑树的问题。一个prim算法就搞定了。。。。
#include<cstdio>
#include<cstring>
using namespace std;
int map[30][30];
int selected[30];
int prim(int n)
{
int sum=0;
selected[1]=1;
int next;
int len=99999999;
for(int i=1;i<n;i++)
{
len=99999999;
for(int j=1;j<=n;j++)
{
if(selected[j])
{
for(int t=1;t<=n;t++)
{
if(!selected[t]&&map[j][t]<len)
{
next=t;len=map[j][t];
}
}
}
}
selected[next]=1;
sum+=len;
}
return sum;
}
int main()
{
//freopen("in.txt","r",stdin);
int M;
scanf("%d",&M);
while(M-->0)
{
memset(selected,0,sizeof(selected));
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(i==j)map[i][j]=0;
else map[i][j]=99999999;
}
}
int a,b,c;
while(scanf("%d%d%d",&a,&b,&c),a&&b&&c)
{
map[a][b]=c;
map[b][a]=c;
}
int len=prim(n);
printf("%d\n",len);
}
return 0;
}