-
Notifications
You must be signed in to change notification settings - Fork 1
/
planet-queries-i.cpp
105 lines (88 loc) · 1.86 KB
/
planet-queries-i.cpp
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
#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
typedef vector<lli> vi;
class Graph
{
vi adj;
vi cycle;
lli nodes;
public:
Graph(lli _nodes, vi _adj)
{
nodes = _nodes;
adj.assign(_adj.begin(), _adj.end());
cycle.resize(_nodes + 1, 0);
}
void preprocess()
{
for (lli i = 1; i <= nodes; i++)
{
lli x = adj[i];
lli count = 0;
bool failedToReturn = false;
while (x != i)
{
count++;
cycle[i]++;
x = adj[x];
if (count > nodes)
{
failedToReturn = true;
break;
}
}
cycle[i]++;
if (failedToReturn)
{
cycle[i] = 0;
}
}
}
lli destinationNode(lli planet, lli distance)
{
lli x = planet;
lli endgame = false;
while (distance)
{
if (cycle[x] == 0 || endgame)
{
x = adj[x];
distance--;
continue;
}
if (cycle[x] == 1)
{
return x;
}
distance = distance % cycle[x];
endgame = true;
}
return x;
}
};
void task()
{
lli lenPlanets, lenQueries;
cin >> lenPlanets >> lenQueries;
vi adj(lenPlanets + 1, 0);
for (lli i = 1; i <= lenPlanets; i++)
{
cin >> adj[i];
}
Graph g(lenPlanets, adj);
g.preprocess();
lli planet, distance;
for (lli i = 0; i < lenQueries; i++)
{
cin >> planet >> distance;
cout << g.destinationNode(planet, distance) << '\n';
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
task();
return 0;
}