Cod sursa(job #1209412)

Utilizator 2dorTudor Ciurca 2dor Data 17 iulie 2014 16:51:21
Problema Andrei Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.58 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;

ifstream fin("andrei.in");
ofstream fout("andrei.out");

const int MAXN = 100005;
vector<int> G[2 * MAXN], actual_component;
vector< vector<int> > Components;
stack<int> S;
int N, M, indexCount, indx[2 * MAXN], level[2 * MAXN];
bool in_stack[2 * MAXN], TruthValue[2 * MAXN];

inline int non(int x) {
    return x > N ? x - N : x + N;
}

inline void AddEdge(int A, int B) {
    G[ non(A) ].push_back( B );
    G[ non(B) ].push_back( A );
}

void Read() {
    fin >> N >> M;
    int A, B, C;
    for (int i = 0; i < M; ++i) {
        fin >> A >> B >> C;
        switch (C) {
            case 0:
                AddEdge(A, B);
                break;
            case 1:
                AddEdge(non(A), non(B));
                break;
            default:
                AddEdge(non(A), B);
                AddEdge(A, non(B));
                break;
        }
    }
}

void Tarjan(int father) {
    indx[father] = level[father] = indexCount++;
    S.push(father); in_stack[father] = true;
    vector<int>::iterator it;
    for (it = G[father].begin(); it != G[father].end(); ++it) {
        if (indx[*it] == -1) {
            Tarjan(*it);
            level[father] = min(level[father], level[*it]);
        }else if (in_stack[*it]) {
            level[father] = min(level[father], level[*it]);
        }
    }
    if (indx[father] == level[father]) {
        actual_component.clear();
        int node;
        do {
            node = S.top();
            S.pop(); in_stack[node] = false;
            actual_component.push_back(node);
        }while (father != node);
        Components.push_back( actual_component );
    }
}

void Solve() {
    for (int i = 1; i <= 2 * N; ++i)
        indx[i] = -1;
    for (int i = 1; i <= 2 * N; ++i)
        if (indx[i] == -1)
            Tarjan(i);
    for (int i = Components.size() - 1; i >= 0; --i) {
        for (size_t j = 0; j < Components[i].size(); ++j) {
            if (not TruthValue[ Components[i][j] ] && not TruthValue[ non(Components[i][j]) ]) {
                TruthValue[ Components[i][j] ] = false;
                TruthValue[ non(Components[i][j]) ] = true;
            }
        }
    }
}

void Write() {
    for (int i = 1; i <= N; ++i)
        fout << not TruthValue[i] << ' ';
    fout << '\n';
}

int main() {
    Read();
    cerr << "Data read.\n";
    Solve();
    cerr << "Solved.\n";
    Write();
    cerr << "Data Written.\n";
    fin.close();
    fout.close();
    return 0;
}