Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <stack>
- using namespace std;
- void dfs(int r, vector<bool>& used, vector<vector<int>>& g, vector<int>& way) {
- stack<pair<int, int>> s;
- s.push(make_pair(r, -1));
- used[r] = true;
- while (!s.empty()) {
- int v = s.top().first;
- if(!way.empty() && way.back() != v || way.empty()) way.push_back(v);
- bool find = false;
- for (int i = 0; i < g[v].size(); ++i) {
- int to = g[v][i];
- if (used[to] == false) {
- find = true;
- used[to] = true;
- s.push(make_pair(to, v));
- }
- }
- if (!find) {
- if (way.back() != s.top().second) way.push_back(s.top().second);
- s.pop();
- }
- }
- }
- int main() {
- int n, m, r;
- cin >> n >> m >> r;
- vector<vector<int>> g(n);
- vector<bool> used(n, false);
- vector<int> way;
- for (int i = 0; i < m; ++i) {
- int a, b;
- cin >> a >> b;
- --a, --b;
- g[a].push_back(b);
- g[b].push_back(a);
- }
- dfs(r - 1, used, g, way);
- way.pop_back();
- cout << way.size() << endl;
- for (auto x : way) cout << x + 1 << " ";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement