HDU 2122 Ice_cream’s world III

来源:互联网 发布:天下x天下 人祸和知彼 编辑:程序博客网 时间:2024/06/15 04:00
Ice_cream’s world IIICrawling in process...Crawling failedTime Limit:1000MS    Memory Limit:32768KB     64bit IO Format:%I64d & %I64u
SubmitStatus Practice HDU 2122 uDebug

Description

Input

Output

Sample Input

Sample Output

Hint

Description

ice_cream’s world becomes stronger and stronger; every road is built as undirected. The queen enjoys traveling around her world; the queen’s requirement is like II problem, beautifies the roads, by which there are some ways from every city to the capital. The project’s cost should be as less as better.

Input

Every case have two integers N and M (N<=1000, M<=10000) meaning N cities and M roads, the cities numbered 0…N-1, following N lines, each line contain three integers S, T and C, meaning S connected with T have a road will cost C.

Output

If Wiskey can’t satisfy the queen’s requirement, you must be output “impossible”, otherwise, print the minimum cost in this project. After every case print one blank.

Sample Input

2 10 1 104 0

Sample Output

10impossible 
分析:求一颗最小生成树,使用Kruskal算法很快可以解决,不过最好考虑一下两个城市之间是不是有多条路。
代码:
#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>using namespace std;struct note{int start, end, len;};note road[10005];int pre[1005], n, m;int find(int x){int r = x;while (r != pre[r])r = pre[r];while (pre[x] != r){int j = pre[x];pre[x] = r;x = j;}return r;}bool cmp(note a, note b){return a.len < b.len;}int main(){while (scanf("%d%d", &n, &m) != EOF){for (int i = 0; i < n; ++i)pre[i] = i;for (int i = 0; i < m;++i)scanf("%d%d%d", &road[i].start, &road[i].end, &road[i].len);sort(road, road + m, cmp);int ans = 0, cnt = 0;for (int i = 0; i < m; ++i){if (find(road[i].start) != find(road[i].end)){ans += road[i].len;pre[find(road[i].start)] = find(road[i].end);cnt++;}}bool isOk = true;int fa = find(0);for (int i = 1; i < n; ++i){if (fa != find(i)){isOk = false;break;}}if (!isOk)printf("impossible\n\n");elseprintf("%d\n\n", ans);}return 0;}

0 0
原创粉丝点击