-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path612e.cpp
More file actions
79 lines (72 loc) · 2.19 KB
/
Copy path612e.cpp
File metadata and controls
79 lines (72 loc) · 2.19 KB
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
#pragma optimize("O3")
#include <bits/stdc++.h>
using namespace std;
#define all(x) begin(x), end(x)
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vll;
typedef vector<vll> vvll;
typedef vector<bool> vb;
typedef vector<vb> vvb;
int main() {
cin.tie(0)->sync_with_stdio(0);
int n; cin >> n;
vi p(n);
for (int i = 0; i < n; i++) {
cin >> p[i];
p[i]--;
}
vb visited(n);
vvi cycles;
map<int, vi> even_pairings;
for (int i = 0; i < n; i++) {
if (!visited[i]) {
vi cycle;
int cur = i;
while (!visited[cur]) {
visited[cur] = true;
cycle.push_back(cur);
cur = p[cur];
}
if (cycle.size() % 2 == 1) {
vi square_root_cycle(cycle.size());
for (int j = 0; j < cycle.size(); j++) {
square_root_cycle[(j*2) % cycle.size()] = cycle[j];
}
cycles.push_back(square_root_cycle);
} else {
if (even_pairings.count(cycle.size())) {
vi square_root_cycle(cycle.size() * 2);
vi other_cycle = even_pairings[cycle.size()];
for (int j = 0; j < cycle.size(); j++) {
square_root_cycle[(2*j)] = cycle[j];
}
for (int j = 0; j < cycle.size(); j++) {
square_root_cycle[(2*j) + 1] = other_cycle[j];
}
cycles.push_back(square_root_cycle);
even_pairings.erase(cycle.size());
} else {
even_pairings[cycle.size()] = cycle;
}
}
}
}
if (even_pairings.size() != 0) {
cout << -1 << endl;
} else {
vi ans(n);
for (vi cycle : cycles) {
for (int i = 0; i < cycle.size(); i++) {
ans[cycle[i]] = cycle[(i+1)%cycle.size()] + 1;
}
}
for (auto x : ans) {
cout << x << " ";
}
cout << endl;
}
}