hdu6178Monkeys-(贪心+读入优化)

题解:这是树上的最大二分匹配,因为这颗树是连通的所以,可以直接从叶子节点开始向上贪心,每两个配一对即可

记得用读入优化即可。

之前写的HK算法现在过不了

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<vector>
#include<queue>
using namespace std;
inline char nc(){
    static char buf[100000],*p1=buf,*p2=buf;
    return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;
}
inline int _read(){
    char ch=nc();int sum=0;
    while(!(ch>='0'&&ch<='9'))ch=nc();
    while(ch>='0'&&ch<='9')sum=sum*10+ch-48,ch=nc();
    return sum;
}
const int mx = 100005;
const int inf = 0x3f3f3f3f;
int n,k;
int p[mx];
int vis[mx];
int solve(){
    int ans = 0;
    for(int i = n; i>=2; i--)
        if(!vis[p[i]]&&!vis[i]){
            ans++;
            vis[i] = 1;
            vis[p[i]] = 1;
        }
    if(2*ans>=k)
        return (k+1)/2;
    return k-ans;
}
int main(){
    int t;
    t = _read();
    while(t--){
        n = _read();
        k = _read();
        memset(vis,0,sizeof(vis));
        //memset(son,0,sizeof(son));
        for(int i = 2; i <= n; i++){
            int u;
            u = _read();
            p[i] = u;
        }
        printf("%d\n",solve());
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值