Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 4014 | Accepted: 1653 |
Description
Input
- The first line gives the length of cable on the spool as a real number.
- The second line contains the number of houses, N
- The next N lines give the name of each house's owner. Each name consists of up to 20 characters {a–z,A–Z,0–9} and contains no whitespace or punctuation.
- Next line: M, number of paths between houses
- next M lines in the form
< house name A > < house name B > < distance >
Where the two house names match two different names in the list above and the distance is a positive real number. There will not be two paths between the same pair of houses.
Output
Not enough cable
If there is enough cable, then output
Need < X > miles of cable
Print X to the nearest tenth of a mile (0.1).
Sample Input
100.0 4 Jones Smiths Howards Wangs 5 Jones Smiths 2.0 Jones Howards 4.2 Jones Wangs 6.7 Howards Wangs 4.0 Smiths Wangs 10.0
Sample Output
Need 10.2 miles of cable
Source
//Kruskal算法
//真奇怪!G++居然不过,C++就过了!
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
#define N 500
struct point {
int u, v;
double w;
}pnt[N];
int set[N], rank[N];
char name[N][22];
bool cmp(struct point p1, struct point p2) {
return p1.w < p2.w;
}
void make_set(int n) {
for(int i = 0; i <= n; i++) {
set[i] = i;
rank[i] = 1;
}
}
int find_set(int x) {
if(x != set[x]) return set[x] = find_set(set[x]);
return set[x];
}
void merge(int x, int y) {
int xx = find_set(x);
int yy = find_set(y);
if(xx == yy) return;
if(rank[xx] > rank[yy]) {
set[yy] = xx;
rank[xx] += rank[yy];
} else {
set[xx] = yy;
rank[yy] += rank[xx];
}
}
int get_num(char *str, int n) {
for(int i = 1; i <= n; i++) {
if(strcmp(str, name[i]) == 0)
return i;
}
return 0;
}
int main()
{
int i, m, n, u, v;
double len, min_len = 0.0, w;
char str1[22], str2[22];
while(cin>>len) {
cin>>m;
make_set(m);
for(i = 1; i <= m; i++)
cin>>name[i];
cin>>n;
for(i = 0; i < n; i++) {
cin>>str1>>str2>>w;
u = get_num(str1, m); v = get_num(str2, m);
pnt[i].u = u; pnt[i].v = v; pnt[i].w = w;
}
sort(pnt, pnt+n, cmp);
for(i = 0; i < n; i++) {
if(find_set(pnt[i].u) != find_set(pnt[i].v)) {
min_len += pnt[i].w;
merge(pnt[i].u, pnt[i].v);
}
}
if(len >= min_len)
printf("Need %.1lf miles of cable\n", min_len);
else
printf("Not enough cable\n");
}
return 0;
}