Today is Ignatius' birthday. He invites a lot of friends. Now it's dinner time. Ignatius wants to know how many tables he needs at least. You have to notice that not all the friends know each other, and all the friends do not want to stay with strangers.
One important rule for this problem is that if I tell you A knows B, and B knows C, that means A, B, C know each other, so they can stay in one table.
For example: If I tell you A knows B, B knows C, and D knows E, so A, B, C can stay in one table, and D, E have to stay in the other one. So Ignatius needs 2 tables at least.
One important rule for this problem is that if I tell you A knows B, and B knows C, that means A, B, C know each other, so they can stay in one table.
For example: If I tell you A knows B, B knows C, and D knows E, so A, B, C can stay in one table, and D, E have to stay in the other one. So Ignatius needs 2 tables at least.
2 5 3 1 2 2 3 4 5 5 1 2 5
24
并查集的入门题,和HDU1232-畅通工程类似的题目。
AC代码:
#include<iostream> #include<string> #include<algorithm> using namespace std; int pre[1005]; bool k[1005]; int find(int x) { int r = x; while (pre[r]!=r) { r = pre[r]; } int i = x, j; while (pre[i] != r) { j = pre[i]; pre[i] = r; i = j; } return r; } void join(int x, int y) { int fx = find(x), fy = find(y); if (fx!=fy) { pre[fy] = fx; } } int main() { int t; cin >> t; while (t--) { int m, n; cin >> n >> m; int i; for(i=1;i<=n;i++) { pre[i] = i; } int a, b; for (i = 1; i <= m; i++) { cin >> a >> b; join(a, b); } memset(k, 0, sizeof(k)); for (i = 1; i <= n; i++) { k[find(i)] = 1; } int count = 0; for (i=1,count=0;i<=n;i++) { if (k[i]) { count++; } } cout << count << endl; } return 0 }