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
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include<bits/stdc++.h>
using namespace std;

const int N = 1e3+77;

typedef pair<int,int> pii;

int zly[N];
int res[N];
int zlycount = 1;
bool dasie = true;

int p[N];

int freud(int v) {
	if(p[v] != v)
		p[v] = freud(p[v]);
	return p[v];
}

void onion(int v, int w) {
	v = freud(v);
	w = freud(w);
	p[v] = w;
}

vector<int> vertex_box[N];
vector<pii> edges_box[N], revedges_box[N];
bool dod[N];

void jebaj(vector<int> vertexes, vector<pii> edges, vector<pii> revedges, int last = 0) {
	/*cout << "wierzcholki:";
	for(int v: vertexes) cout << v << " ";
	cout << endl;*/
	
	zlycount++;
	
	for(auto e: edges)
		zly[e.first] = zlycount;
	
	for(auto e: revedges)
		zly[e.second] = zlycount;
	
	vector<int> korzenie;
	for(int v: vertexes) if(zly[v] < zlycount) {
		korzenie.push_back(v);
	}

	//cout << "korzenie_size = " << korzenie.size() << endl;

	if(korzenie.size() > 1) {
		for(int i=0;i<(int)korzenie.size()-1;i++) {
			res[korzenie[i]] = last;
			dod[korzenie[i]] = 1;
			last = korzenie[i];
		}
	}

	if((int)korzenie.size() == 0) {
		dasie = false;
		return;
	}

	int korzen = korzenie[korzenie.size()-1];
	dod[korzen] = 1;
	//cout << "korzen " << korzen << endl;

	res[korzen] = last;

	for(int v: vertexes) if(v != korzen) {
		p[v] = v;
		vertex_box[v].clear();
		edges_box[v].clear();
		revedges_box[v].clear();
	}


	for(pii e: edges) if(!dod[e.first] and !dod[e.second])
		onion(e.first, e.second);

	for(int v: vertexes) if(!dod[v])
		vertex_box[freud(v)].push_back(v);

	for(pii e: edges) if(!dod[e.first] and !dod[e.second] and freud(e.first) == freud(e.second))
		edges_box[freud(e.first)].push_back(e);

	for(pii e: revedges) if(!dod[e.first] and !dod[e.second] and freud(e.first) == freud(e.second))
		revedges_box[freud(e.first)].push_back(e);

	for(int v: vertexes) if(!dod[v] and vertex_box[v].size() > 0) { 
		jebaj(vertex_box[v], edges_box[v], revedges_box[v], korzen);
	}
}

int main () {
	ios_base::sync_with_stdio(false);
	cin.tie(0);

	int n,m;
	cin >> n >> m;

	vector<int> vertexes;
	vector<pii> edges, revedges;

	char c;
	int a,b;
	for(int i=0;i<m;i++) {
		cin >> a >> b >> c;
		if(c == 'T')
			edges.emplace_back(a,b);
		else
			revedges.emplace_back(a,b);
	}

	for(int i=1;i<=n;i++)
		vertexes.push_back(i);

	jebaj(vertexes, edges, revedges);

	if(dasie) {
		#ifndef TESTING	
		for(int i=1;i<=n;i++)
			cout << res[i] << "\n";
		#endif
		#ifdef TESTING
		cout << "TAK\n";
		#endif
	} else {
		cout << "NIE\n";
	}
}