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
#include <cstdio>
#include <map>
#include <vector>
#include <set>

using namespace std;

int parent[1009];

vector<int> need[1009];
vector<int> rneed[1009];
vector<int> cant[1009];

void dfs(set<int>& vertices, map<int, int>& result, int v, int c){
	result[v]=c;
	for(auto u:need[v]){
		if(vertices.count(u)){
			if(result.count(u)==0){
				dfs(vertices, result, u, c);
			}
		}
	}
	for(auto u:rneed[v]){
		if(vertices.count(u)){
			if(result.count(u)==0){
				dfs(vertices, result, u, c);
			}
		}
	}
}

bool solve(set<int>& vertices, int par){
	map<int, bool> director; // Can vertex i be a director of all?
	for(auto v:vertices){
		director[v]=true;
	}
	for(auto v:vertices){
		for(auto u:need[v]){
			if(vertices.count(u)){
				// v wants someone above, so v cannot be director.
				director[v]=false;
			}
		}
		for(auto u:cant[v]){
			if(vertices.count(u)){
				// v doesn't want u above, so u cannot be a director.
				director[u]=false;
			}
		}
	}
	set<int> directors;
	for(auto v:vertices){
		if(director[v]){
			directors.insert(v);
			parent[v]=par;
			par=v;
		}
	}
	if(directors.size()==0){
		return false;
	}
	for(auto d:directors){
		vertices.erase(d);
	}
	map<int, int> component;
	int c=0;
	for(auto v:vertices){
		if(component.count(v)==0){
			dfs(vertices, component, v, c++);
		}
	}
	vector<set<int>> components;
	components.resize(c);
	for(auto v:vertices){
		components[component[v]].insert(v);
	}
	for(auto& comp:components){
		if(!solve(comp, par)){
			return false;
		}
	}
	return true;
}

int main(){
	int n,m;
	scanf("%d %d",&n,&m);
	for(int i=0;i<m;i++){
		char s[10];
		int a, b;
		scanf("%d %d %s",&a,&b,s);
		if(s[0]=='T'){
			need[a].push_back(b);
			rneed[b].push_back(a);
		}
		else{
			cant[a].push_back(b);
		}
	}
	set<int> vertices;
	for(int i=1;i<=n;i++){
		vertices.insert(i);
		parent[i]=-1;
	}
	if(!solve(vertices, 0)){
		printf("NIE\n");
		fprintf(stderr, "reason - no viable directors\n");
		return 0;
	}
	for(int i=1;i<=n;i++){
		printf("%d\n", parent[i]);
	}
}