1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <cstdio>
#include <vector>

using namespace std;

int n, m;
vector <int> v[1003]; // boss_out
vector <int> w[1003]; // boss_in
vector <int> t[1003]; // nboss_in

int res[1003];
int part[1003];
int color = 0;

const char MGR     = 1;
const char NO_MGR  = 2;

// znajdź słabe spójne składowe
void make_weakc(int k, int p) {
    if (part[k] == p) {
        part[k] = color;
        for (int i = 0; i < v[k].size(); i++) {
            make_weakc(v[k][i], p);
        }
        for (int i = 0; i < w[k].size(); i++) {
            make_weakc(w[k][i], p);
        }
    }
}

// wygraj ;)
int proceed(int k, int p) {
    // find the boss
    int boss = 0;
    for (int i = 1; i <= n; i++) if (part[i] == p) {
        int bo = 0, nbi = 0;
        for (int j = 0; j < v[i].size(); j++) if (part[v[i][j]] == p) {
            bo++;
        }
        for (int j = 0; j < t[i].size(); j++) if (part[t[i][j]] == p) {
            nbi++;
        }
        if (bo == 0 && nbi == 0) {
            boss = i;
            break;
        }
    }

    if (boss == 0) return -1;

    // usuń bossa
    res[boss] = k;
    part[boss] = -1;

    // get słabe spójne składowe and remember till where they are here
    for (int i = 1; i <= n; i++) if (part[i] == p) {
        ++color;
        make_weakc(i, p);
        if (proceed(boss, color) == -1) {
            return -1;
        }
    }
    return 0;
}

// maine
int main() {
    scanf("%d%d", &n, &m);
    for (int i = 0; i < m; i++) {
        int a, b; char c[2];
        scanf("%d%d%s", &a, &b, c);
        if (c[0] == 'T') {
            v[a].push_back(b);
            w[b].push_back(a);            
        } else {
            t[b].push_back(a);
        }
    }
    if (proceed(0, 0) != -1) {
        for (int i = 1; i <= n; i++) {
            printf("%d\n", res[i]);
        }
    } else {
        printf("NIE\n");
    }
    return 0;
}