Title Description
I lived in a city where n people, any two people who know is the enemy not friends, but also to meet:
1, my friend's friend is my friend;
2, the enemy of my enemy is my friend;
All are friends of people of a gang. Tell you this n m pieces of information about an individual that is a friend of two people, two people or a certain enemy, you write a program to calculate the maximum number of cities may have a gang?
Input Format
The first line n and m, 1 <n <1000,1≤m≤100000;
The m rows, each behavior p, x, y, p is 0 or 1, p is 0, x and y are represented by friends, p is 1, x and y are represented by the enemy.
Output Format
An integer representing the n individual may have up to several gangs.
SAMPLE INPUT
6 4
1 1 4
0 3 5
0 4 6
1 1 2
Sample Output
3
answer
If the input is between two friends, it would direct the merger; otherwise we will not able to save the first alas, have finished entering, then merge all the enemies to everyone.
#include <iostream> #include <cstdio> #define MAX_N 1000 #define MAX_M 100000 using namespace std; int n; int m; int h[MAX_N + 5], p[MAX_M + MAX_M + 5], t[MAX_M + MAX_M + 5]; int r[MAX_N + 5]; int c[MAX_N + 5]; int ans; int Root(int x) { int R = x, tmp; while(R != r[R]) R = r[R]; while(x != r[x]) tmp = r[x], r[x] = R, x = tmp; return R; } int main() { scanf("%d%d", &n, &m); for(register int i = 1; i <= n; ++i) { r[i] = i; } int f, x, y; for(register int i = 1; i <= m; ++i) { scanf("%d%d%d", &f, &x, &y); if(f) { t[i] = y; p[i] = h[x]; h[x] = i; t[i + m] = x; p[i + m] = h[y]; h[y] = i + m; } else { if(Root(x) != Root(y)) { r[Root(y)] = Root(x); } } } for(register int i = 1; i <= n; ++i) { x = t[h[i]]; for(register int j = h[i]; j; j = p[j]) { if(Root(x) != Root(t[j])) { r[Root(t[j])] = Root(x); } } } for(register int i = 1; i <= n; ++i) { c[Root(i)] = 1; } for(register int i = 1; i <= n; ++i) { ans += c[i]; } printf("%d", ans); return 0; }