跳到正文

题解

题解 CF547D 【Mike and Fish】

Kinandra约 3 分钟
原文
文章信息与版本

文章信息

发布
2020年1月29日
收录
2026年10月1日
更新
2026年11月11日
篇幅
约 3 分钟
获赞
32
题目
CF547D

版本

  1. v1当前

标签: 图论, 欧拉回路.

我们转化一下问题: 将点看成连接其横坐标和纵坐标的边, 我们为每一条边定向, 使得每一个点的入度与出度的差的绝对值不超过 11 .

这个很容易可以转化成一个欧拉回路的问题: 显然度数为偶数的点入度等于出度, 而度数为奇数的点入出度恰好差 11 . 我们将度数为奇数的点连一条虚拟边到一个虚拟点, 由于的度数为奇数的点必然是偶数个, 那么虚拟点的度数也为偶数, 我们对新图跑欧拉回路对边定向即可.

时间复杂度 O(n)\mathcal O(n).

C++
#include <bits/stdc++.h>
using namespace std;
int read();
int n;
int hd[400005], nx[800005], to[800005], cnt;
int deg[800005];
void add(int f, int t) {
    nx[++cnt] = hd[f], hd[f] = cnt, to[cnt] = t, ++deg[f];
}
struct E {
    int u, v;
    void init() { u = read(), v = read() + 200000, add(u, v), add(v, u); }
} p[200005];
bool vis[800005];
int res[200005];

int tcc;
void dfs(int u) {
    for (int &i = hd[u], e; i; i = nx[i])
        if (!vis[e = i >> 1])
            vis[e] = 1, (e <= n ? res[e] = i & 1 : 0), dfs(to[i]);
}

int main() {
    n = read(), cnt = 1;
    for (int i = 1; i <= n; ++i) p[i].init();
    for (int i = 1; i <= 400000; ++i)
        if (deg[i] & 1) add(0, i), add(i, 0);
    for (int i = 1; i <= 400000; ++i) dfs(i);
    for (int i = 1; i <= n; ++i) putchar(res[i] ? 'r' : 'b');
    return 0;
}
const int _SIZE = 1 << 22;
char ibuf[_SIZE], *iS = ibuf, *iT = ibuf;
#define gc                                                         \
    (iS == iT ? iT = ((iS = ibuf) + fread(ibuf, 1, _SIZE, stdin)), \
     (iS == iT ? EOF : *iS++) : *iS++)
int read() {
    int x = 0, f = 1;
    char c = gc;
    while (!isdigit(c)) f = (c == '-') ? -1 : f, c = gc;
    while (isdigit(c)) x = x * 10 + c - '0', c = gc;
    return x * f;
}
原文
存档评论2 条抓取于