CF1100E Andrew and Taxi

时间:2022-04-27 12:32:51

题目地址:CF1100E Andrew and Taxi

二分,每次取到一个 \(mid\) ,只保留长度 \(>mid\) 的边

dfs判环,若有环,说明 \(ans>mid\) ,否则 \(ans≤mid\)

找到 \(ans\) 后,对长度 \(>ans\) 的边进行一次拓扑排序,对多余的点直接接在拓扑排序序列后面即可

对从 \(x\) 到 \(y\) 的长度 \(≤ans\) 的边,如果 \(x\) 在拓扑排序序列中的位置比 \(y\) 后,则这条边需取反

时间复杂度 \(O(n\ log\ C)\)

#include <bits/stdc++.h>
using namespace std;
const int N = 100006;
int n, m, mx = 0, d[N], b[N], t;
int Head[N], Edge[N], Leng[N], Next[N], Pose[N];
vector<int> ans;
bool v[N], w[N];
queue<int> q;

inline void add(int x, int y, int z, int i) {
    Edge[i] = y;
    Leng[i] = z;
    Next[i] = Head[x];
    Head[x] = i;
    Pose[i] = x;
}

bool dfs(int x, int now) {
    v[x] = 1;
    w[x] = 1;
    for (int i = Head[x]; i; i = Next[i]) {
        int y = Edge[i], z = Leng[i];
        if (z <= now) continue;
        if (w[y] || !dfs(y, now)) return 0;
    }
    w[x] = 0;
    return 1;
}

inline bool pd(int now) {
    memset(v, 0, sizeof(v));
    memset(w, 0, sizeof(w));
    for (int i = 1; i <= n; i++)
        if (!v[i] && !dfs(i, now)) return 0;
    return 1;
}

void topsort(int now) {
    for (int i = 1; i <= n; i++)
        if (!d[i]) q.push(i);
    while (q.size()) {
        int x = q.front();
        q.pop();
        b[x] = ++t;
        for (int i = Head[x]; i; i = Next[i]) {
            int y = Edge[i], z = Leng[i];
            if (z > now && !--d[y]) q.push(y);
        }
    }
}

unsigned int work(int now) {
    for (int i = 1; i <= m; i++) {
        int y = Edge[i], z = Leng[i];
        if (z > now) ++d[y];
    }
    topsort(now);
    for (int i = 1; i <= n; i++)
        if (!b[i]) b[i] = ++t;
    for (int i = 1; i <= m; i++) {
        int x = Pose[i], y = Edge[i], z = Leng[i];
        if (z <= now && b[x] > b[y]) ans.push_back(i);
    }
    return ans.size();
}

int main() {
    cin >> n >> m;
    for (int i = 1; i <= m; i++) {
        int x, y, z;
        scanf("%d %d %d", &x, &y, &z);
        add(x, y, z, i);
        mx = max(mx, z);
    }
    int l = 0, r = mx;
    while (l < r) {
        int mid = (l + r) >> 1;
        if (pd(mid)) r = mid;
        else l = mid + 1;
    }
    cout << l << " " << work(l) << endl;
    for (unsigned int i = 0; i < ans.size(); i++)
        printf("%d ", ans[i]);
    return 0;
}