1 4 2 3 2 1 2 4 2 2 4
1 4
好在这里的path长度都是1,如果要访问的k个点的数目少于直径上的点的数目,那么路径长度就是k - 1;如果遍历完直径也到不了k个点,那么就需要访问直径以外的点,那么需要走回头路
#include <map> #include <set> #include <list> #include <stack> #include <vector> #include <queue> #include <cmath> #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int N = 100010; const int inf = 0x3f3f3f3f; struct node { int next; int to; }edge[N << 1]; int n, m; int end_p; bool vis[N]; int dist[N]; int head[N]; int tot; int maxs; void addedge(int from, int to) { edge[tot].to = to; edge[tot].next = head[from]; head[from] = tot++; } void build() { int u, v; memset( head, -1, sizeof(head) ); tot = 0; for (int i = 0; i < n - 1; ++i) { scanf("%d%d", &u, &v); addedge(u, v); addedge(v, u); } } void bfs(int s) { queue<int>qu; memset( vis, 0, sizeof(vis) ); while ( !qu.empty() ) { qu.pop(); } qu.push(s); dist[s] = 0; vis[s] = 1; maxs = 0; while ( !qu.empty() ) { int u = qu.front(); qu.pop(); for (int i = head[u]; i != -1; i = edge[i].next) { int v = edge[i].to; if (!vis[v]) { vis[v] = 1; dist[v] = dist[u] + 1; qu.push(v); if (maxs < dist[v]) { maxs = dist[v]; end_p = v; } } } } } int main() { int t, k; scanf("%d", &t); while (t--) { scanf("%d%d", &n, &m); build(); bfs(1); bfs(end_p); int cnt = maxs + 1; while (m--) { scanf("%d", &k); if(k <= cnt) { printf("%d\n", k - 1); continue; } printf("%d\n", maxs + 2 * (k - cnt) ); } } return 0; }