解题思路:
注意事项:
参考代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 7;
int p[N];
bool vis[N] = {false};
vector<int> G[N];
int parent(int x) {
int res;
if (x == p[x]) {
res = x;
}
else {
res = parent(p[x]);
p[x] = res;
}
return res;
}
void dfs(int a, int b, vector<int> &buf) {
if (vis[a]) {
return;
}
vis[a] = true;
buf.push_back(a);
if (a == b) {
sort(buf.begin(), buf.end());
for (int i = 0; i < buf.size(); i++) {
cout << buf[i] << " ";
}
cout << endl;
return;
}
for (int i = 0; i < G[a].size(); i++) {
dfs(G[a][i], b, buf);
}
buf.pop_back();
vis[a] = false;
}
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
p[i] = i;
}
int a, b;
for (int i = 0; i < n; i++) {
cin >> a >> b;
int fA = parent(a);
int fB = parent(b);
if (fA == fB) {
vector<int> buf;
dfs(a, b, buf);
break;
} else {
p[fB] = fA;
G[a].push_back(b);
G[b].push_back(a);
}
}
return 0;
}
0.0分
0 人评分
点我有惊喜!你懂得!浏览:2114 |
C语言程序设计教程(第三版)课后习题5.8 (C语言代码)浏览:981 |
A+B for Input-Output Practice (IV) (C++代码)浏览:713 |
小明A+B (C语言代码)浏览:1316 |
C语言程序设计教程(第三版)课后习题6.7 (C语言代码)浏览:548 |
IP判断 (C语言代码)浏览:819 |
C语言程序设计教程(第三版)课后习题1.5 (C语言代码)浏览:701 |
矩阵加法 (C语言代码)浏览:1768 |
Tom数 (C语言代码)浏览:581 |
C语言程序设计教程(第三版)课后习题12.6 (C语言代码)浏览:732 |