TOJ 比赛C题 Visiting Cows (TJU 2011 Exercise Contest 04)

C. Visiting Cows
Time Limit: 1.0 Seconds Memory Limit: 65536K
Total Runs: 61 Accepted Runs: 21 Multiple test files



Description

After many weeks of hard work, Bessie is finally getting a vacation! Being the most social cow in the herd, she wishes to visit her N (1 ≤ N ≤ 50,000) cow friends conveniently numbered 1..N. The cows have set up quite an unusual road network with exactly N-1 roads connecting pairs of cows C1 and C2 (1 ≤ C1N; 1 ≤ C2N; C1C2) in such a way that there exists a unique path of roads between any two cows.

FJ wants Bessie to come back to the farm soon; thus, he has instructed Bessie that if two cows are directly connected by a road, she may not visit them both. Of course, Bessie would like her vacation to be as long as possible, so she would like to determine the maximum number of cows she can visit.

Input

  • Line 1: A single integer: N
  • Lines 2..N: Each line describes a single road with two space-separated integers: C1 and C2

Output

  • Line 1: A single integer representing the maximum number of cows that Bessie can visit.

Input

Output

4

我是利用树状DP过的,不过Kash给我说,用topsort也可以过。。

我的代码:

#include<stdio.h>

#include<algorithm>

#include<vector>

#include<string.h>

using namespace std;

int dp[50005][2];

vector<int>v[50005];

bool flag[50005];

int min(int a,int b)

{

if(a>b)

return b;

else

return a;

}

void dfs(int p)

{

int i;

for(i=0;i<v[p].size();i++)

{

if(!flag[v[p][i]])

{

flag[v[p][i]]=true;

dfs(v[p][i]);

}

}

if(v[p].size()==0)

{

dp[p][0]=0;

dp[p][1]=1;

}

else

{

for(i=0;i<v[p].size();i++)

{

int j=v[p][i];

dp[p][1]=dp[p][1]+min(dp[j][1],dp[j][0]);

dp[p][0]=dp[p][0]+dp[j][1];

}

dp[p][1]++;

}

}

int main()

{

int a,b,n,i;

while(scanf("%d",&n)!=EOF)

{

memset(flag,0,sizeof(flag));

for(i=0;i<50005;i++)

v[i].clear();

memset(dp,0,sizeof(dp));

memset(flag,0,sizeof(flag));

for(i=0;i<n-1;i++)

{

scanf("%d%d",&a,&b);

v[a].push_back(b);

v[b].push_back(a);

}

flag[1]=true;

dfs(1);

printf("%d/n",n-min(dp[1][0],dp[1][1]));

}

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值