题解 LOJ2391 「JOISC 2017 Day 1」港口设施

· · 个人记录

先考虑一下暴力怎么做:

现在问题转变为如何优化连边。直接线段树是可以做的,但事实上有更加优美的做法。

我们建图的目的是判断是否为二分图和求连通块个数,则当存在 (x, y), (x, z), (w, y), (w, z) 时,(w, y) 不需要建出来——因为我们知道 y, z 应当染成同一颜色。

在本题的建图中,若 \exists [a, b], [c, d], a < c < b < d,则 \forall [c', d'], c < c' < b < d',我们可以在连边 ([a, b], [c', d']) 后将其视作不存在——因为此时 [c, d], [c', d'] 一定同色。

考虑遍历 1 \sim 2n,遇到一个 l 时插入,遇到一个 r 时删除并加边。

设 nxt_i 表示按 l 升序排序后,现在编号为 i 的区间后面最后一个一定与 i 同色的区间编号。

加边时,我们需要把当前未被删除的区间中 l > a 的后缀向当前区间 [a, b] 连边。

加边时,我们连完 i 后依次找出编号 > nxt_i 的下一个未被删除的区间(这个可以并查集维护),最后令这些 nxt_i 为当前最大线段编号即可。

那时间复杂度如何呢?注意到我们对 nxt_i 的操作实质上是并查集的路径压缩,于是总边数为 O(n \log n),可以接受。

时间复杂度为 O(n \log n)。常数不知比线段树小到哪里去了。

代码:

#include <stdio.h>

typedef struct {
    int nxt;
    int end;
} Edge;

const int mod = 1e9 + 7;
int cnt = 0;
int root[1000007], nxt[1000007], refl[2000007], refr[2000007], id[1000007], head[1000007], color[1000007];
bool vis[1000007];
Edge edge[19000007];

inline void init(int n){
    for (int i = 1; i <= n; i++){
        root[i] = nxt[i] = i;
    }
}

inline int read(){
    int ans = 0;
    char ch = getchar();
    while (ch < '0' || ch > '9'){
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9'){
        ans = ans * 10 + (ch ^ 48);
        ch = getchar();
    }
    return ans;
}

int get_root(int x){
    if (root[x] == x) return x;
    return root[x] = get_root(root[x]);
}

inline void add_edge(int start, int end){
    cnt++;
    edge[cnt].nxt = head[start];
    head[start] = cnt;
    edge[cnt].end = end;
}

inline void merge(int x, int y){
    int root_x = get_root(x), root_y = get_root(y);
    if (root_x != root_y) root[root_x] = root_y;
}

bool dfs(int u, int cur_color){
    if (vis[u]) return color[u] == cur_color;
    vis[u] = true;
    color[u] = cur_color;
    cur_color ^= 1;
    for (int i = head[u]; i != 0; i = edge[i].nxt){
        int x = edge[i].end;
        if (!dfs(x, cur_color)) return false;
    }
    return true;
}

int main(){
    int n = read(), m = n * 2, cnt = 0, ans = 1;
    init(n + 1);
    for (int i = 1; i <= n; i++){
        int a = read(), b = read();
        refl[a] = refr[b] = i;
    }
    for (int i = 1; i <= m; i++){
        if (refl[i] != 0){
            id[refl[i]] = ++cnt;
        } else {
            merge(id[refr[i]], id[refr[i]] + 1);
            for (int j = get_root(id[refr[i]]); j <= cnt; ){
                int t = nxt[j];
                add_edge(id[refr[i]], j);
                add_edge(j, id[refr[i]]);
                nxt[j] = cnt;
                j = get_root(t + 1);
            }
        }
    }
    for (int i = 1; i <= n; i++){
        if (!vis[i]){
            if (!dfs(i, 0)){
                printf("0");
                return 0;
            }
            ans = ans * 2 % mod;
        }
    }
    printf("%d", ans);
    return 0;
}