Cod sursa(job #2438153)

Utilizator CharacterMeCharacter Me CharacterMe Data 11 iulie 2019 14:43:38
Problema Andrei Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.31 kb
#include <iostream>
#include <cstdio>
#include <vector>
#define node first
#define colour second
using namespace std;
int n, m, i, j, code[100001];
vector<pair<int, int> > graph[100001];
vector<int> list;
bool check[100001];
bool dfs(int node, int val);
int main()
{
    freopen("andrei.in", "r", stdin);
    freopen("andrei.out", "w", stdout);
    scanf("%d%d", &n, &m);
    for(i=1; i<=m; ++i){
        int x, y, z;
        scanf("%d%d%d", &x, &y, &z);
        graph[x].push_back({y, z});
        graph[y].push_back({x, z});
    }
    for(i=1; i<=n; ++i)
        if(!check[i]){
            list.clear();
            if(!dfs(i, 0)){
                for(auto j:list) check[j]=false;
                list.clear();
                dfs(i, 1);
            }
        }
    for(i=1; i<=n; ++i) printf("%d ", code[i]);
    return 0;
}
bool dfs(int node, int val){
    if(check[node]==true) return val==code[node];
    code[node]=val;
    check[node]=true; list.push_back(node);
    for(auto j:graph[node]){
        if(j.colour==0){
            if(val==0 && !dfs(j.node, 1)) return false;
        }
        else if(j.colour==1){
            if(val==1 && !dfs(j.node, 0)) return false;
        }
        else {
            if(!dfs(j.node, 1-val)) return false;
        }
    }
    return true;
}