http://acm.hdu.edu.cn/showproblem.php?pid=1213
题意:
这个问题的一个重要规则是,如果我告诉你A知道B,B知道C,这意味着A,B,C知道对方,所以他们可以留在一个桌子。
例如:如果我告诉你A知道B,B知道C,D知道E,所以A,B,C可以留在一个桌子中,D,E必须留在另一个桌子中。所以Ignatius至少需要2个桌子。
思路:
并查集模板题。
#include<iostream> using namespace std; int p[1005]; int find(int x) { return p[x] == x ? x : find(p[x]); } void Unions(int x, int y) { p[x] = y; } int main() { //freopen("D:\txt.txt", "r", stdin); int T, a, b, n, m; cin >> T; while (T--) { cin >> n >> m; for (int i = 1; i <= n; i++) p[i] = i; for (int i = 0; i < m; i++) { cin >> a >> b; int x = find(a); int y = find(b); if (x != y) Unions(x, y); } int ans = 0; for (int i = 1; i <= n;i++) if (p[i] == i) ans++; cout << ans << endl; } return 0; }