CodeChef Chef and Reversing

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
#include <bits/stdc++.h>
using namespace std;
using PII = pair<int, int>;
const int N = 100001;
int n, m, x, y, dist[N];
vector<PII> g[N];
priority_queue<PII, vector<PII>, greater<PII>> q;
int main() {
scanf("%d%d", &n, &m);
while (m--) {
scanf("%d%d", &x, &y);
g[x].emplace_back(y, 0);
g[y].emplace_back(x, 1);
}
memset(dist, 0x3f, sizeof(dist));
q.emplace(0, 1);
dist[1] = 0;
while (q.size()) {
auto p = q.top(); q.pop();
int d = p.first, u = p.second;
for (auto &x : g[u]) {
int v = x.first, w = x.second;
if (dist[v] > d + w) {
dist[v] = d + w;
q.emplace(dist[v], v);
}
}
}
printf("%d\n", dist[n] == 0x3f3f3f3f ? -1 : dist[n]);
return 0;
}
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
#include <bits/stdc++.h>
using namespace std;
using PII = pair<int, int>;
const int N = 100001;
int n, m, x, y, dist[N];
vector<PII> g[N];
queue<int> q;
bool vis[N];
int main() {
scanf("%d%d", &n, &m);
while (m--) {
scanf("%d%d", &x, &y);
g[x].emplace_back(y, 0);
g[y].emplace_back(x, 1);
}
memset(dist, 0x3f, sizeof(dist));
dist[1] = 0;
q.emplace(1);
while (q.size()) {
int u = q.front(); q.pop();
vis[u] = false;
for (auto &x : g[u]) {
int v = x.first, w = x.second;
if (dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
if (!vis[v])
q.emplace(v), vis[v] = true;
}
}
}
printf("%d\n", dist[n] == 0x3f3f3f3f ? -1 : dist[n]);
return 0;
}
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
#include <bits/stdc++.h>
using namespace std;
const int N = 100001;
int n, m, x, y, dist[N];
vector<pair<int, int>> g[N];
deque<int> q;
int main() {
scanf("%d%d", &n, &m);
while (m--) {
scanf("%d%d", &x, &y);
g[x].emplace_back(y, 0);
g[y].emplace_back(x, 1);
}
memset(dist, 0x3f, sizeof(dist));
q.emplace_back(1);
dist[1] = 0;
while (q.size()) {
auto u = q.front(); q.pop_front();
for (auto &x : g[u]) {
int v = x.first, w = x.second;
if (dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
if (w) q.emplace_back(v);
else q.emplace_front(v);
}
}
}
printf("%d\n", dist[n] == 0x3f3f3f3f ? -1 : dist[n]);
return 0;
}