GESP C++ 八级历年真题题解
GESP C++ 八级历年真题题解

1. 区间
题目大意
给定长度为 的序列 ,有 次询问,每次给出 ,要求统计 在区间 中出现了多少次。
解题思路
对每个数值 ,记录它在序列中出现的所有下标,并保持升序。
对于询问 ,只需要在 的下标数组中二分:
也就是:
代码
#include <bits/stdc++.h>
#define LOG(FMT...) fprintf(stderr, FMT)
using namespace std;
typedef long long LL;
const int N = 1e6 + 10;
int read(){
int x = 0,f = 1; char ch = getchar();
while (ch < '0' || ch > '9') {if (ch == '-') f = -1; ch = getchar();}
while (ch >= '0' && ch <= '9') {x = x * 10 + ch - '0'; ch = getchar();}
return x * f;
}
int n, q;
inline void solve() {
cin >> n;
map<int, vector<int> > mp;
for (int i = 1; i <= n; i++) {
int x;
cin >> x;
mp[x].push_back(i);
}
cin >> q;
while (q--) {
int l, r, x;
cin >> l >> r >> x;
if (!mp.count(x)) {
printf("0\n");
continue;
}
vector<int> &v = mp[x];
int Ans = upper_bound(v.begin(), v.end(), r) - lower_bound(v.begin(), v.end(), l);
printf("%d\n", Ans);
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int _ = 1; cin >> _;
while (_--) solve();
return 0;
}
2. 小杨的旅游
题目大意
给定一棵 个点的树,部分城市有传送门。任意两个传送门城市之间可以花费 时间互相传送。每次询问从 到 的最短时间。
解题思路
从 到 有两种方案:
- 直接在树上走,距离为:
- 从 走到最近的传送门,传送到另一个传送门,再走到 :
其中 表示点 到最近传送门的树上距离。
所以答案为:
树上距离用 求,最近传送门距离用多源 求。
代码
#include <bits/stdc++.h>
#define LOG(FMT...) fprintf(stderr, FMT)
using namespace std;
typedef long long LL;
const int N = 2e5 + 10, inf = 1e9 + 10;
int read(){
int x = 0,f = 1; char ch = getchar();
while (ch < '0' || ch > '9') {if (ch == '-') f = -1; ch = getchar();}
while (ch >= '0' && ch <= '9') {x = x * 10 + ch - '0'; ch = getchar();}
return x * f;
}
int n, k, q;
vector<int> G[N];
int dep[N], fa[20][N];
int dis[N];
void bfs_dep() {
queue<int> que;
que.push(1);
dep[1] = 1;
fa[0][1] = 1;
while (!que.empty()) {
int u = que.front();
que.pop();
for (int v : G[u]) {
if (v == fa[0][u]) continue;
fa[0][v] = u;
dep[v] = dep[u] + 1;
que.push(v);
}
}
for (int j = 1; j < 20; j++) {
for (int i = 1; i <= n; i++) {
fa[j][i] = fa[j - 1][fa[j - 1][i]];
}
}
}
int lca(int x, int y) {
if (dep[x] < dep[y]) swap(x, y);
int d = dep[x] - dep[y];
for (int j = 19; j >= 0; j--) {
if ((d >> j) & 1) x = fa[j][x];
}
if (x == y) return x;
for (int j = 19; j >= 0; j--) {
if (fa[j][x] != fa[j][y]) {
x = fa[j][x];
y = fa[j][y];
}
}
return fa[0][x];
}
int dist(int x, int y) {
int z = lca(x, y);
return dep[x] + dep[y] - 2 * dep[z];
}
inline void solve() {
cin >> n >> k >> q;
for (int i = 1, x, y; i < n; i++) {
cin >> x >> y;
G[x].push_back(y);
G[y].push_back(x);
}
bfs_dep();
queue<int> que;
for (int i = 1; i <= n; i++) dis[i] = inf;
for (int i = 1, x; i <= k; i++) {
cin >> x;
dis[x] = 0;
que.push(x);
}
while (!que.empty()) {
int u = que.front();
que.pop();
for (int v : G[u]) {
if (dis[v] > dis[u] + 1) {
dis[v] = dis[u] + 1;
que.push(v);
}
}
}
while (q--) {
int u, v;
cin >> u >> v;
int Ans = dist(u






