求助!WA 19, 23
查看原帖
求助!WA 19, 23
480060
saihaze楼主2021/10/16 21:57

代码如下。

#include <cstddef>
#include <cstring>
#include <iostream>
#include <queue>
#include <vector>

using namespace std;

using i64 = long long;
constexpr int maxn = 100001;

struct edge {
    int to;
    edge *next;
} *edges[maxn];

void create_edge(int from, int to) {
    static edge pool[maxn], *pos = pool;
    pos->to = to, pos->next = edges[from];
    edges[from] = pos++;
}

bool in_loop[maxn], visit[maxn];

int mark_loop(int x, int from, int dep) {
    static int depth[maxn];
    depth[x] = dep, visit[x] = true;
    for (edge *e = edges[x]; e; e = e->next) {
        if (e->to == from) {
            continue;
        }
        if (visit[e->to]) {
            in_loop[x] = true;
            return depth[e->to];
        } else {
            int tmp = mark_loop(e->to, x, dep + 1);
            if (tmp) {
                if (dep >= tmp) {
                    in_loop[x] = true;
                }
                return tmp;
            }
        }
    }
    return 0;
}

vector<int> ans;
bool found = false;

void dfs(int x, int mi) {
    if (x > mi) {
        return;
    }
    visit[x] = true;
    ans.push_back(x);
    priority_queue<int> q;
    for (edge *e = edges[x]; e; e = e->next) {
        if (!visit[e->to]) {
            q.push(-e->to);
        }
    }
    if (!found && in_loop[x]) {
        found = true;
        bool flag = true;
        while (q.size()) {
            int y = -q.top(); q.pop();
            if (in_loop[y]) {
                if (!visit[y]) {
                    dfs(y, flag ? -q.top() : 0x3f3f3f3f);
                }
                flag = false;
            } else {
                dfs(y, 0x3f3f3f3f);
            }
        }
    } else {
        while (q.size()) {
            int y = -q.top(); q.pop();
            if (in_loop[y]) {
                dfs(y, mi);
            } else {
                dfs(y, 0x3f3f3f3f);
            }
        }
    }
}

int main() {
    ios::sync_with_stdio(false);
    int n, m; cin >> n >> m;
    for (int i = 0; i < m; i++) {
        int u, v; cin >> u >> v;
        create_edge(u, v);
        create_edge(v, u);
    }
    mark_loop(1, 0, 1);
    memset(visit, 0, sizeof(visit));
    dfs(1, 0x3f3f3f3f);
    for (int x: ans) {
        cout << x << ' ';
    }
    cout << endl;
}
2021/10/16 21:57
加载中...