Dyd's Blog

He who has a strong enough why can bear almost any how.

luoguP3906 Geodetic集合

大水题

Geodetic集合

水题(主要是 $n$ 太小了),直接给代码

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
#include <bits/stdc++.h>
#define all(x) (x).begin(), (x).end()
using namespace std;
const int N = 40 + 5;
int n, m, que;
struct Que
{
int u, v, id;
bool operator < (const Que &t) const
{
return u == t.u ? u < t.u : v < t.v;
}
} qq[N * N];
vector<int> ans[N * N];
bool vis[N];
int dis[N];
struct Edge
{
int ne, ver;
} e[(N * N) << 1];
int h[N], idx = 0;
void add(int x, int y)
{
e[idx] = (Edge){h[x], y}, h[x] = idx++;
}
void bfs(int star)
{
for (int i = 1; i <= n; ++i)
dis[i] = 0;
queue<int> q;
dis[star] = 1;
q.push(star);
int x, y;
while (!q.empty())
{
x = q.front(), q.pop();
for (int i = h[x]; i != -1; i = e[i].ne)
if (!dis[y = e[i].ver])
{
dis[y] = dis[x] + 1;
q.push(y);
}
}
}
void work(int id, int star)
{
queue<int> q;
q.push(star);
int x, y;
for (int i = 1; i <= n; ++i)
vis[i] = false;
ans[id].push_back(star);
vis[star] = true;
while (!q.empty())
{
x = q.front(), q.pop();
for (int i = h[x]; i != -1; i = e[i].ne)
if (!vis[y = e[i].ver] && dis[y] == dis[x] - 1)
{
ans[id].push_back(y);
vis[y] = true;
q.push(y);
}
}
}
int main()
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; ++i)
h[i] = -1;
for (int i = 1, a, b; i <= m; ++i)
{
scanf("%d%d", &a, &b);
add(a, b), add(b, a);
}
scanf("%d", &que);
for (int i = 1; i <= que; ++i)
{
scanf("%d%d", &qq[i].u, &qq[i].v);
qq[i].id = i;
if (qq[i].u > qq[i].v)
swap(qq[i].u, qq[i].v);
}
sort(qq + 1, qq + 1 + que);
for (int i = 1, now = 0; i <= que; ++i)
{
if (now != qq[i].u)
{
bfs(qq[i].u);
now = qq[i].u;
}
work(qq[i].id, qq[i].v);
}
for (int i = 1; i <= que; ++i)
{
sort(all(ans[i]));
for (int j : ans[i])
printf("%d ", j);
putchar('\n');
}
return 0;
}