您的位置:首页 > 其它

hdu-6178-Monkeys(fast IO)

2017-08-25 12:33 330 查看
题意:一颗有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
4000
(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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: