Problem Description
小雷有个特殊的癖好,平时喜欢收藏各种稀奇古怪的东西,譬如。。。。,还有。。。。,也包括。。。。。小雷是一个喜欢分享的童鞋,这次小雷又给大家带来一套神奇的东西,那就是举世无双的冰茶几!
顾名思义,这些茶几被冰冻住了,最主要的是他们是易碎品,毕竟被冻住了。因此小雷要很小心翼翼的移动他们。一些茶几是冻在一起的,因此一套冰茶几分为好几部分,并且如果茶几A与B冻在一起,B与C冻在一起,那么A与C也就冻在了,即冰冻状态有传递性,ABC此时会看作一个整体。
为了保证冰茶几的完整性,小雷每次只能移动一整块冰茶几,也就是冰冻在一起的一部分。小雷想知道他需要搬几次才能全部搬到实验室,你能帮小雷快速计算出答案么?
Input
多组输入,先输入组数T(1 < = T < = 200)。
对于每组输入,先输入一个整数n(1 < = n < = 100000),k(0 < = k < = 100000),茶几编号1~n。
之后k行,每行两数x,y(1 < = x,y < = n),表示第x个茶几和第y个茶几冰冻在一起。
Output
对于每组输入,先输出”Case z: ”(不带引号)表示组数,再输出一个整数,表示小雷需要搬动的次数。
Example Input
3 3 1 1 2 5 2 1 2 3 4 5 2 1 2 2 3
Example Output
Case 1: 2 Case 2: 3 Case 3: 3
Hint
Author
2015年第五届ACM趣味编程循环赛(第一场) by LeiQ
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 1e5 +5; const int INF = 0x3f3f3f3f; int pre[maxn], deep[maxn]; int Find(int x) { return pre[x] == x ? x : Find(pre[x]); } void Unite(int x, int y) { x = Find(x); y = Find(y); if(x == y) { return; } if(deep[x] < deep[y]) { pre[x] = y; } else { pre[y] = x; if(deep[x] == deep[y]) { deep[x]++; } } } void CSH(ll n) { memset(deep, 0, sizeof(deep)); for(int i = 1; i <= n; i++) { pre[i] = i; } } void SR(ll k) { while(k--) { int x, y; scanf("%d%d", &x, &y); Unite(x, y); } } void SC(int t, ll n) { int ans = 0; for(int i = 1; i <= n; i++) { if(i == pre[i]) { ans++; } } printf("Case %d: %d\n", t, ans); } int main() { int T; scanf("%d", &T); for(int i = 1; i <= T; i++) { ll n, k; scanf("%lld%lld", &n, &k); CSH(n); SR(k); SC(i, n); } return 0; } /*************************************************** User name: Result: Accepted Take time: 104ms Take Memory: 976KB Submit time: 2018-02-01 09:21:46 ****************************************************/