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
132
133
134
135
136
137
138
139
| struct SCC {
int n;
vector<vector<int> > g, rg, ng, scc; // rg: 逆グラフ, ng: 分解後のグラフ
vector<int> res; // scc: 強連結成分に属する頂点, res:強連結成分の番号
bool used[100005];
SCC(int _n) {
n = _n;
g.resize(n); rg.resize(n) ; scc.resize(n); res.resize(n);
}
SCC(const vector<vector<int> > &g) : n(g.size()), g(g), rg(n), scc(n), res(n) {
rep(i, n) {
rep(j, g[i].size()) rg[g[i][j]].push_back(i);
}
}
// i-jに辺を追加する
void add(int i, int j) {
g[i].push_back(j);
rg[j].push_back(i);
}
vector<int> vs;
void dfs(int v) {
used[v] = true;
rep(i, g[v].size()) {
if(!used[ g[v][i] ]) dfs(g[v][i]);
}
vs.push_back(v);
}
void rdfs(int v, int k) {
used[v] = true;
res[v] = k;
scc[k].push_back(v);
rep(i, rg[v].size()) {
if(!used[ rg[v][i] ]) rdfs(rg[v][i], k);
}
}
void ng_make(int k) {
ng.resize(k);
rep(i, n) {
set<int> S;
rep(j, g[i].size()) {
int to = g[i][j];
if(res[i] == res[to]) continue;
if(S.find(res[to]) != S.end()) continue;
ng[res[i]].push_back(res[to]);
S.insert(res[to]);
}
}
}
int run() {
memset(used, 0, sizeof(used));
rep(i, n) {
if (!used[i]) dfs(i);
}
memset(used, 0, sizeof(used));
int k = 0;
for (int i = vs.size()-1; i >= 0; i--) {
if (!used[vs[i]]) rdfs(vs[i], k++);
}
ng_make(k);
return k;
}
};
bool used[55];
vector< vector<int> > ng;
vector<int> out;
void dfs(int cur) {
used[cur] = true;
rep(i, ng[cur].size()) {
int v = ng[cur][i];
if(!used[v]) dfs(v);
}
out.push_back(cur);
}
class Autohamil {
public:
string check(vector <int> z0, vector <int> z1) {
int n = z0.size();
SCC scc(n);
rep(i, n) {
if(i != z0[i]) scc.add(i, z0[i]);
if(i != z1[i]) scc.add(i, z1[i]);
}
int m = scc.run();
ng.resize(m);
rep(i, m) {
ng[i].resize(scc.ng[i].size());
rep(j, scc.ng[i].size()) {
ng[i][j] = scc.ng[i][j];
}
}
int cnt[55];
memset(cnt, 0, sizeof(cnt));
rep(i, m) {
rep(j, ng[i].size()) {
cnt[ng[i][j]]++;
}
}
REP(i, 1, m) {
if(cnt[i] == 0) return "Does not exist";
}
int s = scc.res[0];
memset(used, 0, sizeof(used));
out.clear();
dfs(s);
reverse(out.begin(), out.end());
if(out[0] != 0) return "Does not exist";
rep(i, out.size()-1) {
bool ch = false;
rep(j, ng[out[i]].size()) {
if(ng[out[i]][j] == out[i+1]) {
ch = true;
}
}
if(ch) continue;
return "Does not exist";
}
return "Exists";
}
};
|