Luogu 3530 [POI2012]FES-Festival

我是真的不会写差分约束啊呜呜呜……

BZOJ 2788被权限了。

首先对于第一个限制$x + 1 = y$,可以转化成$x + 1 leq y leq x + 1$,

所以连一条$(y, x, -1)$,再连一条$(x, y, 1)$。

第二个状态即为$x leq y$,连边$(y, x, 0)$。

如果有负环就无解了。

发现在这个图中,每一个强连通分量都互相不干扰,我们可以缩点找出所有的强连通分量,然后找到里面的最长路$ + 1$累加到答案中去。

时间复杂度$O(能过)$。

感觉$POI$的数据挺满的,我的代码跑得挺慢的。

Code:

#include <cstdio>
#include <cstring>
using namespace std;

const int N = 605;
const int M = 3e5 + 5;

int n, m1, m2, tot = 0, head[N], f[N][N];
int ans = 0, scc = 0, bel[N], dfsc = 0, dfn[N], low[N], top = 0, sta[N];
int sCnt, s[N];
bool vis[N];

struct Edge {
    int to, nxt;
} e[M];

inline void add(int from, int to) {
    e[++tot].to = to;
    e[tot].nxt = head[from];
    head[from] = tot;
}

inline void read(int &X) {
    X = 0; char ch = 0; int op = 1;
    for(; ch > '9' || ch < '0'; ch = getchar())
        if(ch == '-') op = -1;
    for(; ch >= '0' && ch <= '9'; ch = getchar())
        X = (X << 3) + (X << 1) + ch - 48;
    X *= op;
}

inline void chkMin(int &x, int y) {
    if(y < x) x = y;
}

inline int min(int x, int y) {
    return x > y ? y : x;
}

inline void chkMax(int &x, int y) {
    if(y > x) x = y;
}

inline void solve() {
    int res = 0;
    for(int i = 1; i <= sCnt; i++)
        for(int j = 1; j <= sCnt; j++) {
            int x = s[i], y = s[j];
            chkMax(res, f[x][y]);
        }
    ans += res + 1;
}

void tarjan(int x) {
    dfn[x] = low[x] = ++dfsc;
    sta[++top] = x, vis[x] = 1;
    for(int i = head[x]; i; i = e[i].nxt) {
        int y = e[i].to;
        if(!dfn[y]) {
            tarjan(y);
            low[x] = min(low[x], low[y]);
        } else if(vis[y]) low[x] = min(low[x], dfn[y]);
    }

    if(low[x] == dfn[x]) {
        ++scc; sCnt = 0;
        for(; sta[top + 1] != x; --top) {
            vis[sta[top]] = 0;
            bel[sta[top]] = scc;
            s[++sCnt] = sta[top];
        }
        solve();
    }
}

int main() {
    read(n), read(m1), read(m2);
    memset(f, 0x3f, sizeof(f));
    for(int x, y, i = 1; i <= m1; i++) {
        read(x), read(y);
        add(x, y), add(y, x);
        chkMin(f[x][y], 1), chkMin(f[y][x], -1);
    }
    for(int x, y, i = 1; i <= m2; i++) {
        read(x), read(y);
        add(y, x);
        chkMin(f[y][x], 0);
    }

    for(int i = 1; i <= n; i++) f[i][i] = 0;
    for(int k = 1; k <= n; k++)
        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= n; j++)
                chkMin(f[i][j], f[i][k] + f[k][j]);
    
    for(int i = 1; i <= n; i++)
        if(f[i][i] < 0) {
            puts("NIE");
            return 0;
        }
    
    for(int i = 1; i <= n; i++)
        if(!dfn[i]) tarjan(i);

    printf("%d
", ans);
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/CzxingcHen/p/9800095.html