思路:用一个关系数组记录当前结点与其父亲的关系,0表示同类,1表示不同类
AC代码:
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <cmath> #include <queue> #include <stack> #include <vector> #include <map> #include <set> #include <deque> #include <cctype> #define LL long long #define INF 0x7fffffff using namespace std; const int maxn = 100005; int T; int n, m; int pa[maxn]; int rela[maxn];//±íʾ½áµãÓëÆ丸Ç׵ĹØϵ£¬Í¬ÀàΪ0£¬²»Í¬ÀàΪ1£¬³õʼʱͬÀà int find(int x) { int t = pa[x]; if(pa[x] == x) { return x; } else { pa[x] = find(pa[x]); rela[x] = (rela[x] == rela[t]) ? 0 : 1;//µÈÓÚ0±íʾÊôÓÚͬһÀà return pa[x]; } } int main() { scanf("%d", &T); while(T --) { scanf("%d %d", &n, &m); for(int i = 1; i <= n; i ++) { //³õʼ»¯ pa[i] = i; rela[i] = 0; } for(int i = 0; i < m; i ++) { int a, b; char op[5]; scanf("%s %d %d", op, &a, &b); int fa = find(a), fb = find(b); if(op[0] == 'A') { if(fa != fb) { printf("Not sure yet.\n"); } else if(rela[a] == rela[b]){ cout << "In the same gang." << endl; } else { cout << "In different gangs." << endl; } } else { if(fa != fb) { pa[fa] = fb; rela[fa] = (rela[a] == rela[b]) ? 1 : 0;//a,b¿Ï¶¨²»ÔÚͬһ¸ö°ïÅÉ } } } } return 0; }
时间: 2024-10-10 05:49:50