题意:给一棵树,有N个节点,树上有K个猴子,每个节点最多有一个猴子,从树上的边中去掉一些边,留下尽可能少的边使得每个猴子都至少和一个其他猴子相连,求最少留的边数。
DFS,类似于一个简单的树形DP,从叶子节点往根节点找,如果没有相连的就相连,如果有就继续向上找。这样搜完以后得到的结果是最多有几对猴子可以两两相连。然后判断如果能两两相连的猴子数比总的猴子少,那么剩下的只能和那些两两相连的连。如果比总的猴子多,那么就全部两两相连就行。
这题要用输入输出外挂,不然会TLE……第一次用这玩意儿……
#include <bits/stdc++.h>
namespace fastIO{
#define BUF_SIZE 100000000
//fread -> read
bool IOerror=0;
inline char nc() {
static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE;
if (p1==pend){
p1=buf;
pend=buf+fread(buf,1,BUF_SIZE,stdin);
if (pend==p1){
IOerror=1;
return -1;
}
}
return *p1++;
}
inline bool blank(char ch){
return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';
}
inline void read(int &x){
char ch;
while (blank(ch = nc()));
if (IOerror)
return;
for (x=ch-'0';(ch=nc())>='0'&&ch<='9';x=x*10+ch-'0');
}
#undef BUF_SIZE
};
using namespace fastIO;
using namespace std;
const int maxn=100000+10;
int T;
int N,K;
int ans=0;
struct Edge{
int to;
int next;
}edge[2*maxn];
int cntE=0;
int head[maxn];
bool vis[maxn];
void addedge(int u,int v){
edge[cntE].to=v;
edge[cntE].next=head[u];
head[u]=cntE++;
edge[cntE].to=u;
edge[cntE].next=head[v];
head[v]=cntE++;
}
bool dfs(int x){
vis[x]=true;
bool flag=false;
for (int i=head[x];i!=-1;i=edge[i].next){
int v=edge[i].to;
if (vis[v]) continue;
vis[v]=true;
if (dfs(v))
flag=true;
}
if (flag){
ans++;
return false;
}
else
return true;
}
int main(){
// freopen("1.txt","r",stdin);
read(T);
while (T--){
memset(head,-1,sizeof(head));
memset(vis,false,sizeof(vis));
cntE=0;
read(N);
read(K);
for (int i=1;i<=N-1;i++){
int x;
read(x);
addedge(x,i+1);
}
ans=0;
vis[1]=true;
dfs(1);
if (2*ans<=K){
printf("%d\n",ans+K-2*ans);
}
else
printf("%d\n",(K-1)/2+1);
}
}