E. Cars (二分图染色, 拓扑排序,有向无环图的判定)

Problem - 1635E - Codeforces

#include <iostream>
#include <algorithm>
#include <cstring>
#include <set>
#include <unordered_map>
#include <vector>
#include <queue>
#include <functional>
#include <cstdio>

using namespace std;

#define ll long long
#define PII pair<int, int>

const int N = 2e5 + 100, M = N << 2;

int h[N], e[M], ne[M], w[M], idx;
int col[N], n, m;

void add(int a, int b, int c) {
    e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}

bool check(int x, int c) {
    col[x] = c;
    for (int i = h[x]; ~i; i = ne[i]) {
        int u = e[i];
        if (!col[u]) {
            if (!check(u, 3 - c)) return false;
        }
        else if (col[u] == c) return false;
    }
    return true;
}

struct Node {
    int a, b, c;
    Node(int x, int y, int z) { a = x, b = y, c = z; }
    Node(){}
};
Node p[N];
int d[N], ans[N];

bool toposort() {
    memset(h, -1, sizeof h);
    idx = 0;
    for (int i = 1; i <= m; i++) {
        int a = p[i].a, b = p[i].b;
        if (p[i].c == 1) {
            if (col[p[i].a] == 1) add(p[i].a, p[i].b, 1), d[b]++;
            else add(p[i].b, p[i].a, 1), d[a]++;
        }
        else {
            if (col[p[i].a] == 1) add(p[i].b, p[i].a, 1), d[a]++;
            else add(p[i].a, p[i].b, 1), d[b]++;
        }
    }
    queue<int>q;
    for (int i = 1; i <= n; i++)
        if (d[i] == 0)
            q.push(i);

    int t = 0;
    while (q.size()) {
        int x = q.front(); q.pop();
        for (int i = h[x]; ~i; i = ne[i]) {
            int u = e[i];
            d[u]--;
            if (d[u] == 0) q.push(u);
        }
        ans[x] = ++t;
    }
    for (int i = 1; i <= n; i ++)
        if (d[i] != 0)
            return false;
    return true;
}

int main() {
    scanf("%d%d", &n, &m);
    memset(h, -1, sizeof h);

    for (int i = 1; i <= m; i++) {
        int c, a, b;
        scanf("%d%d%d", &c, &a, &b);
        add(a, b, c); add(b, a, c);
        if (a > b)swap(a, b);
        p[i] = { a, b, c };
    }

    for (int i = 1; i <= n; i++)
        if (!col[i])
            if (!check(i, 1)) {
                printf("NO\n");
                return 0;
            }

    if (!toposort()) {
        printf("NO\n");
        return 0;
    }

    puts("YES");
    for (int i = 1; i <= n; i++) printf("%s %d\n", col[i] == 1 ? "L" : "R", ans[i]);

    puts("");
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值