Capital Program 剩下k个点的集合,到其它所有点的最大距离最小 拓扑排序
链接:https://ac.nowcoder.com/acm/contest/35146/B
来源:牛客网
题目描述
There is a kingdom that has nnn cities connected by n−1n-1n−1 roads. All roads' length is 111. The King wants to choose an area to be the capital of the kingdom. The area must have exactly kkk connected cities (the area of the capital is a connected component with exactly kkk cities). To show the importance of the capital, the King wants to minimize the maximum value of all the nnn cities.
We define the value of a city as the minimum distance between the city and one city which belongs to the capital. The distance between two cities is the length of the shortest path between them.
输入描述:
The first line of each test contains two integers nnn and kkk (5≤n≤100000,1≤k≤n5 \leq n \leq 100000,1 \leq k \leq n5≤n≤100000,1≤k≤n) --- the number of vertices and the number of cities of the capital, respectively.
Next n−1n-1n−1 lines describe edges: the iii-th line contains two integers ui,viu_i, v_iui,vi (1≤ui,vi≤n,ui≠vi1 \leq u_i,v_i \leq n, u_i \neq v_i1≤ui,vi≤n,ui=vi) --- indices of vertices connected by the iii-th edge.
输出描述:
Print the minimum of the maximum value of all cities.
#include<bits/stdc++.h> using namespace std; const int N = 2e5+10; vector<int>e[N]; int d[N],dist[N]; signed main() { int n,k; cin>>n>>k; for(int i = 1;i<=n-1;i++) { int u,v;cin>>u>>v; e[u].push_back(v);e[v].push_back(u); d[u] ++ ,d[v] ++ ; } queue<int>q; for(int i = 1;i<=n;i++) { if(d[i] == 1)q.push(i),dist[i] = 1; } int ans = 0; int cnt = 0; while(q.size()) { int tmp = q.front();q.pop(); cnt ++ ; if(n - cnt < k) break; ans = max(ans,dist[tmp]); // cout<<d[tmp]<<' '; for(auto it:e[tmp]) { int j = it; dist[j] = max(dist[tmp] + 1,dist[j]); d[j] -- ; if(d[j] == 1) q.push(j); } } // cout<<endl; cout<<ans<<endl; }