hdu-6178-Monkeys(fast IO)

题意:一颗有n个节点的树,然后有K个猴子,一个猴子必须可以走到一个猴子,我们可以将猴子放在树的节点上,在满足一个猴子可以走到另一个猴子的基础上,去掉一些边,使得留下的边最少。

思路:让相邻的边两两配对,看最多能配几对,此时2个猴子只需要一条边,如果配对完之后,还有猴子,那么,每一个猴子将需要一条边与其他的配对好了的相连。dfs搜一遍。(可耻的卡读入)。

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <vector>

#define siz 100005
#define LL long long

namespace fastIO {
	#define BUF_SIZE 100000
	//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';
	}
	template<class T>
	inline void read(T &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;
int n,k;
vector<int>vec[siz];
int cnt = 0;
bool vis[siz];
void dfs(int u,int fa){
    int len = vec[u].size();
    /*if(len == 1 && !vis[fa]){
        vis[fa] = true;
        vis[u] = true;
        ++cnt;
        return ;
    }*/
    //cout<<len<<endl;
    for(int i = 0;i < len;i++){
        if(vec[u][i]!=fa){
            dfs(vec[u][i],u);
        }
    }
    if(!vis[u]&&!vis[fa]){
        vis[u] = vis[fa] = true;
        ++cnt;
    }
}
void solve(){
    cnt = 0;
    memset(vis,false,sizeof(vis));
    dfs(1,-1);
    //cout<<cnt<<" "<<"----"<<endl;
    int ans;
    if(k<=2*cnt){
        ans = k/2 + (k % 2);
    }
    else{
        ans = cnt + k - 2*cnt;
    }
    printf("%d\n",ans);
}
int main()
{
    int tcas;
    read(tcas);
    //scanf("%d",&tcas);
    while(tcas--){
      //scanf("%d%d",&n,&k);
        read(n);
        read(k);
       for(int i=0;i<=n;i++){
            vec[i].clear();
       }
        for(int i=1;i<=n-1;i++){
            int u;
            read(u);
            //scanf("%d",&u);
            vec[u].push_back(i+1);
            vec[i+1].push_back(u);
        }
        /*for(int i=1;i<=n;i++){
            for(int j = 0;j<vec[i].size();j++)
                cout<<vec[i][j]<<" ";
            cout<<endl;
        }*/
        solve();
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值