题意
给出若干区间染两种颜色,求出染色方案使得每个点上不同的颜色种类绝对值不超过1。
思路
将每个区间的l和r连边,跑欧拉回路,因为有跑过去的再跑回来就可以抵消掉颜色的差值。
但有可能不可以形成欧拉回路,这样我们加入虚边,最多只会对答案产生1的差值,不过根据题意这也是合法的。
代码
#include <cstdio>
#include <algorithm>
int n, tot = 1, cnt;
int head[200001], ver[400001], next[400001], id[400001];
int l[100001], r[100001], deg[200001];
int vp[200001], ve[400001];
int x[200001];
int ans[100001];
void add(int u, int v) {
ver[++tot] = v;
next[tot] = head[u];
head[u] = tot;
}
void dfs(int p) {
vp[p] = 1;
for (int i = head[p]; i; i = next[i]) {
if (ve[i]) continue;
ve[i] = ve[i ^ 1] = 1;
ans[id[i]] = (p < ver[i]);
dfs(ver[i]);
}
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d %d", &l[i], &r[i]);
r[i]++;
x[++cnt] = l[i];
x[++cnt] = r[i];
}
std::sort(x + 1, x + cnt + 1);
cnt = std::unique(x + 1, x + cnt + 1) - x - 1;
for (int i = 1; i <= n; i++) {
l[i] = std::lower_bound(x + 1, x + cnt + 1, l[i]) - x;
r[i] = std::lower_bound(x + 1, x + cnt + 1, r[i]) - x;
add(l[i], r[i]);
id[tot] = i;
add(r[i], l[i]);
id[tot] = i;
deg[l[i]]++;
deg[r[i]]++;
}
for (int i = 1, last = 0; i <= cnt; i++) if (deg[i] & 1) {
if (last) add(last, i), add(i, last), last = 0;
else last = i;
}
for (int i = 1; i <= cnt; i++)
if (!vp[i]) dfs(i);
for (int i = 1; i <= n; i++)
printf("%d ", ans[i]);
}