您的位置:首页 > 其它

HDU 6178 Monkeys (贪心+输入挂)

2017-08-27 21:21 337 查看


Monkeys

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 153428/153428 K (Java/Others)

Total Submission(s): 934    Accepted Submission(s): 311


Problem Description

There is a tree having N vertices. In the tree there are K monkeys (K <= N). A vertex can be occupied by at most one monkey. They want to remove some edges and leave minimum edges, but each monkey must be connected to at least one other monkey through the remaining
edges.

Print the minimum possible number of remaining edges.

 

Input

The first line contains an integer T (1 <= T <= 100), the number of test cases. 

Each test case begins with a line containing two integers N and K (2 <= K <= N <= 100000). The second line contains N-1 space-separated integers a1,a2,…,aN−1,
it means that there is an edge between vertex ai and
vertex i+1 (1 <= ai <=
i).

 

Output

For each test case, print the minimum possible number of remaining edges.

 

Sample Input

2
4 4
1 2 3
4 3
1 1 1

 

Sample Output

2
2

 

Source

2017 Multi-University Training Contest
- Team 10 

 

题意:

给你一个图,让你删最多边,使得每只猴子都能找到另一只猴子。

POINT:

在树底开始找成对的点,找到就要,贪心。

再一个输入挂就不TLE了。用了这个就不能用scanf,害我wa了好久。浪费我时间

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <vector>
using namespace std;
#define LL long long
const int maxn = 101000;
int vis[maxn];
int n,m;
vector<int>G[maxn];
int dui=0;
#define FI(n) FastIO::read(n)

namespace FastIO {
const int SIZE = 1 << 16;
char buf[SIZE], obuf[SIZE], str[60];
int bi = SIZE, bn = SIZE, opt;
int read(char *s) {
while (bn) {
for (; bi < bn && buf[bi] <= ' '; bi++);
if (bi < bn) break;
bn = fread(buf, 1, SIZE, stdin);
bi = 0;
}
int sn = 0;
while (bn) {
for (; bi < bn && buf[bi] > ' '; bi++) s[sn++] = buf[bi];
if (bi < bn) break;
bn = fread(buf, 1, SIZE, stdin);
bi = 0;
}
s[sn] = 0;
return sn;
}
bool read(int& x) {
int n = read(str), bf;

if (!n) return 0;
int i = 0; if (str[i] == '-') bf = -1, i++; else bf = 1;
for (x = 0; i < n; i++) x = x * 10 + str[i] - '0';
if (bf < 0) x = -x;
return 1;
}
};
void dfs(int now,int pre)
{
for(int i=0;i<G[now].size();i++)
{
int v=G[now][i];
if(v==pre) continue;
dfs(v,now);
if(vis[v]==0&&vis[now]==0)
{
dui++;
vis[v]=vis[now]=1;
}
}
}
void init()
{
dui=0;
memset(vis,0,sizeof vis);
for(int i=1;i<=maxn;i++)
{
G[i].clear();
}
}

int main()
{
int T;
FI(T);
while(T--)
{
init();
FI(n),FI(m);
for(int i=2;i<=n;i++)
{
int a;
FI(a);
G[i].push_back(a);
G[a].push_back(i);
}
dfs(1,-1);
int ans;
int now=2*dui;
if(m<=now)
{
ans=m/2;
if(m&1) ans++;
}
else
{
ans=dui+m-(dui*2);
}
printf("%d\n",ans);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: