标签:class tac 个人 ++ name first ble can 实现
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 61806 | Accepted: 18734 |
Description
Input
Output
Sample Input
1 5 5 A 1 2 D 1 2 A 1 2 D 2 4 A 1 4
Sample Output
Not sure yet. In different gangs. In the same gang.
n个人,分成两个帮派,给出m次操作,A a b 代表查询ab是否是同一个派别,D a b 代表ab不是同一个派别
通过这个题学习了种类并查集
普通的并查集是将相同的合并为一个祖先,但是本题给的是元素之间的不同关系,可以通过开两倍的数组来实现
合并时 将a+n与b合并 a与b+n合并,代表两者敌对,查询时如果a与b的祖先相同则代表是同一帮派,如果a+n与b的祖先(或a与b+n的祖先)相同则属于对立帮派
本题输入输出cin cout会超时
#include <iostream> #include <string.h> #include <stdio.h> #include <vector> #include <stack> #include <queue> #include <algorithm> #include <math.h> #include <cstdio> using namespace std; int s[200005],t,n,m,i; int findf(int x) { return x==s[x]?x:s[x]=findf(s[x]); } void hebing (int x,int y) { int fx=findf(x); int fy=findf(y); if(fx!=fy) { s[fx]=fy; } } int pd(int x,int y) { if(findf(x)==findf(y)) { return 1; } else { return 0; } } int main() { ios::sync_with_stdio(false); scanf("%d",&t); while(t--) { scanf("%d %d",&n,&m); for(i=1;i<=2*n;i++) { s[i]=i; } while(m--) { int a,b; char S[5]; scanf("%s%d%d",S,&a,&b); if(S[0]==‘D‘) { hebing(a+n,b); hebing(a,b+n); } else { if(pd(a,b)==1) { cout << "In the same gang." << endl; } else if(pd(a,b+n)==1) { cout << "In different gangs." << endl; } else { cout << "Not sure yet." << endl; } } } } }
POJ 1703 Find them, Catch them (种类并查集)
标签:class tac 个人 ++ name first ble can 实现
原文地址:https://www.cnblogs.com/dyhaohaoxuexi/p/12549289.html