-
Notifications
You must be signed in to change notification settings - Fork 1
/
1941g.cpp
105 lines (80 loc) · 1.84 KB
/
1941g.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 <iostream>
#include <map>
#include <set>
#include <vector>
constexpr unsigned oo = ~0u;
template <typename T>
std::istream& operator >>(std::istream& input, std::vector<T>& v)
{
for (T& a : v)
input >> a;
return input;
}
void answer(unsigned x)
{
std::cout << x << '\n';
}
struct Edge {
unsigned u;
unsigned v;
unsigned c;
};
std::istream& operator >>(std::istream& input, Edge& e)
{
return input >> e.u >> e.v >> e.c;
}
void solve(size_t n, std::vector<Edge>& edges, size_t s, size_t t)
{
std::map<unsigned, size_t> c;
for (Edge& e : edges) {
--e.u;
--e.v;
c.emplace(e.c, n + c.size());
e.c = c[e.c];
}
n += c.size();
std::vector<std::vector<std::pair<size_t, unsigned>>> g(n);
for (const Edge& e : edges) {
g[e.u].emplace_back(e.c, 1);
g[e.c].emplace_back(e.u, 0);
g[e.v].emplace_back(e.c, 1);
g[e.c].emplace_back(e.v, 0);
}
std::vector<unsigned> d(n, oo);
std::set<std::pair<unsigned, size_t>> q;
const auto enqueue = [&](size_t u, unsigned w) {
if (w >= d[u])
return;
if (d[u] != oo)
q.erase(std::make_pair(d[u], u));
d[u] = w;
q.emplace(w, u);
};
enqueue(s, 0);
while (!q.empty() && q.begin()->second != t) {
const auto x = *q.begin();
q.erase(q.begin());
for (const auto& v : g[x.second])
enqueue(v.first, x.first + v.second);
}
answer(d[t]);
}
void test_case()
{
size_t n, m;
std::cin >> n >> m;
std::vector<Edge> edges(m);
std::cin >> edges;
unsigned b, e;
std::cin >> b >> e;
solve(n, edges, b-1, e-1);
}
int main()
{
std::cin.tie(nullptr)->sync_with_stdio(false);
size_t t;
std::cin >> t;
while (t-- > 0)
test_case();
return 0;
}