#includeusing namespace std;int pre[3000];int find(int x)//找到祖宗,参数是下标。{int r = x;while (r != pre[r])r = pre[r];return r;}void join(int x, int y){int rx = find(x);int ry = find(y);if(rx!=ry){pre[rx] = ry;}}bool native(int x, int y){int rx = find(x);int ry = find(y);if (rx == ry)return true;elsereturn false;}int main(){int N, M;//N表示有多少人,M表示有多少组亲戚关系。cin >> N >> M;for (int i = 0;i < N;i++){pre[i] = i;}while (M--){int x; int y;cin >> x >> y;join(x, y);}int Q;cin >> Q;while (Q--){int a, b;cin >> a >> b;if (native(a, b))cout << "YES" << endl;elsecout << "NO" << endl;}}
并查集找亲戚
最新推荐文章于 2023-12-24 02:01:48 发布