T2:
题目描述 Description
现在有一棵 n 个节点的树,要求你选出L条路径使得这些路径覆盖的节点数最大,求这个最大节点数。
Subtask1(30):1<=n<=20,1<=L<=3
Subtask2(30):1<=n,L<=3000
Subtask3(40):1<=n,L<=1000000
【输入样例】
17 3
1 2
3 2
2 4
5 2
5 6
5 8
7 8
9 8
5 10
10 13
13 14
10 12
12 11
15 17
15 16
15 10
【输出样例】
13
先找叶子节点,打个标记,抹去叶子节点;再找现在的叶子节点,打标记为(上次标记+1),抹去叶子节点;一直操作下去;最后每个点都被标记了;
对于一条路径,经过标号相同的节点最多经过两个。一共走L条路径,那么一种标号最多走min(L*2,标号总个数)
#include<bits/stdc++.h>
using namespace std;
int n,m,x,y,head,tail,tot,maxs,ans;
int first[1000005],d[1000005],t[1000005],q[1000005],sign[1000005];
struct node{
int next,to;
}e[2000005];
int read(){
int i=0;
char ch;
for(ch=getchar();ch<'0'||ch>'9';ch=getchar());
for(;ch>='0'&&ch<='9';ch=getchar()) i=(i<<3)+(i<<1)+ch-'0';
return i;
}
void inser(int x,int y){
tot++;
e[tot].next=first[x];
first[x]=tot;
e[tot].to=y;
}
int main(){
n=read();m=read()<<1;
for(int i=1;i<=n-1;++i){
x=read();y=read();
inser(x,y);
inser(y,x);
d[x]++;d[y]++;
}
for(int i=1;i<=n;++i) if(d[i]==1) q[++tail]=i;
while(head<tail){
head++;//t[sign[head]]++;
int x=q[head];
for(int u=first[x];u;u=e[u].next){
int to=e[u].to;
d[to]--;
if(d[to]==1) q[++tail]=to,sign[to]=sign[x]+1;
}
}
for(int i=1;i<=n;++i)
t[sign[i]]++;
for(int i=0;t[i];++i) ans+=min(m,t[i]);
cout<<ans<<endl;
}