傳送門
描述
W 市的交通規劃出現了重大問題,市政府下定決心在全市各大交通路口安排疏導員來疏導密集的車流。
但由於人員不足,W 市市長決定只在最需要安排人員的路口安排人員。
具體來說,W 市的交通網絡十分簡單,由 n 個交叉路口和 n−1 條街道構成,交叉路口路口編號依次爲 0,1,…,n−1 。
任意一條街道連接兩個交叉路口,且任意兩個交叉路口間都存在一條路徑互相連接。
經過長期調查,結果顯示,如果一個交叉路口位於 W 市交通網最長路徑上,那麼這個路口必定擁擠不堪。
所謂最長路徑,定義爲某條路徑 p=(v1,v2,…,vk),路徑經過的路口各不相同,且城市中不存在長度大於 k 的路徑(因此最長路徑可能不唯一)。
因此 W 市市長想知道哪些路口位於城市交通網的最長路徑上。
輸入格式
第一行包含一個整數 n。
之後 n−1 行每行兩個整數 u,v,表示編號爲 u 和 v 的路口間存在着一條街道。
輸出格式
輸出包括若干行,每行包括一個整數——某個位於最長路徑上的路口編號。
爲了確保解唯一,請將所有最長路徑上的路口編號按編號順序由小到大依次輸出。
數據範圍
1≤n≤2×105
輸入樣例:
10
0 1
0 2
0 4
0 6
0 7
1 3
2 5
4 8
6 9
輸出樣例:
0
1
2
3
4
5
6
8
9
首先我們找到樹的最長路徑長度,記錄每個點的最長和次長
然後我們根據最長加次長等於答案,然後來找路徑上的點
AC代碼如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=2e5+5;
int h[N],to[2*N],nxt[2*N],tot;
int d1[N],d2[N],an[N],st[N],ans,m;
bool fl[N];
void add(int x,int y) {
to[++tot]=y;
nxt[tot]=h[x];
h[x]=tot;
}
void dp(int x,int fa) {
for(int i=h[x]; i; i=nxt[i]) {
int y=to[i];
if(y==fa) continue;
dp(y,x);
if(d1[y]+1>d1[x])
d2[x]=d1[x],d1[x]=d1[y]+1;
else if(d1[y]+1>d2[x])
d2[x]=d1[y]+1;
}
ans=max(ans,d1[x]+d2[x]);
}
void work(int x,int fa,int len) {
if(fl[x]==0) {
an[++m]=x;
fl[x]=1;
}
for(int i=h[x]; i; i=nxt[i]) {
int y=to[i];
if(y==fa) continue;
if(d1[y]==len-1) work(y,x,len-1);
}
}
void dfs(int x,int fa) {
if(d1[x]+d2[x]==ans) {
if(d1[x]!=d2[x]) work(x,fa,d1[x]);
work(x,fa,d2[x]);
}
for(int i=h[x]; i; i=nxt[i]) {
int y=to[i];
if(y==fa) continue;
dfs(y,x);
}
}
int main() {
int n;
scanf("%d",&n);
for(int i=1; i<=n-1; i++) {
int x,y;
scanf("%d%d",&x,&y);
add(x,y),add(y,x);
}
dp(0,-1);
dfs(0,-1);
sort(an+1,an+m+1);
for(int i=1; i<=m; i++) printf("%d\n",an[i]);
return 0;
}