#include <bits/stdc++.h>
using namespace std;
#define int long long
int n, m, q, p[300005], sz[300005], ans[300005], depth[300005];
vector<int> g[300005], topo;
bool visited[300005], z[300005];
int find(int v) {
	if (p[v] == v) return v;
	return p[v] = find(p[v]);
}
void merge(int u, int v) {
	u = find(u), v = find(v);
	if (u == v) return;
	if (sz[v] < sz[u]) swap(u, v);
	p[u] = v;
	sz[v] += sz[u];
}
void dfs(int v) {
	visited[v] = 1;
	for (const int u : g[v]) {
		depth[u] = max(depth[u], depth[v] + 1);
		if (!visited[u]) dfs(u);
	}
	topo.push_back(v);
}
int32_t main() {
	ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
	cin >> n >> m >> q;
	for (int i = 1; i <= m; i++) p[i] = i, sz[i] = 1;
	while (q--) {
		char c; int a, b; string s; cin >> s;
		stringstream os(s);
		os >> a >> c >> b;
		if (c == '=') merge(a, b);
		else g[a].push_back(b), z[b] = 1;
	}
	
	for (int i = 1; i <= m; i++) {
		int x = i;
		if (z[x] || visited[x]) continue;
		topo.clear(); depth[x] = 1; dfs(x);
		assert(depth[topo[0]] <= n);
		if (depth[topo[0]] == n) {
			reverse(topo.begin(), topo.end());
			for (size_t j = 0; j < topo.size(); j++) {
				ans[find(topo[j])] = depth[topo[j]];
			}
		}
	}
	
	for (int i = 1; i <= m; i++) {
		int res = ans[find(i)];
		if (res == 0) cout << "?\n";
		else cout << 'K' << res << '\n';
	}
}
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... |