题解 LOJ2391 「JOISC 2017 Day 1」港口设施
先考虑一下暴力怎么做:
- 对于所有相交但不包含的区间
i, j ,它们不能在同一个栈内,连边。 - 若最终得到的图不为二分图,无解。
- 否则,答案为
2 的连通块个数次方,因为你指定一个联通块中的一个线段后其他都确定了。
现在问题转变为如何优化连边。直接线段树是可以做的,但事实上有更加优美的做法。
我们建图的目的是判断是否为二分图和求连通块个数,则当存在
在本题的建图中,若
考虑遍历
设
加边时,我们需要把当前未被删除的区间中
加边时,我们连完
那时间复杂度如何呢?注意到我们对
时间复杂度为 常数不知比线段树小到哪里去了。
代码:
#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;
}