您的位置:首页 > 其它

hdu5758Explorer Bo

2016-07-27 21:24 369 查看

链接:http://acm.hdu.edu.cn/showproblem.php?pid=5758

题意:给定一棵n个点的树,每次任选两个点,然后覆盖两点间的所有边,要求选择最少的次数覆盖所有的边,在最少次数的情况下要求覆盖边的次数最小。

分析:要求选择的次数最小那么显然是从叶子到叶子才会使得总体最少。那么就要将叶子为奇或偶分类讨论,先讨论偶数的情况。我们以一个不是叶子的就节点当根,以每个根为过渡点。偶数情况:如果当前儿子的子树中有奇数个叶子那么儿子要和自己连通那么这条边只需要经过一次,如果当前儿子的子树中有偶数个叶子那么儿子要和自己连通那么这条边需要经过两次。奇数情况:只需要在偶数下选择一条只有一个叶子的最长链单独拿来算一次即可。

代码:

#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<bitset>
#include<math.h>
#include<vector>
#include<string>
#include<stdio.h>
#include<cstring>
#include<iostream>
#include<algorithm>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
const int N=100010;
const int mod=100000000;
const int MOD1=1000000007;
const int MOD2=1000000009;
const double EPS=0.00000001;
typedef long long ll;
const ll MOD=1000000007;
const int MAX=1000000010;
const ll INF=1ll<<55;
const double pi=acos(-1.0);
typedef double db;
typedef unsigned long long ull;
int tot,u
,v[2*N],pre[2*N];
void add(int a,int b) {
v[tot]=b;pre[tot]=u[a];u[a]=tot++;
}
int d
,son
,dp
[2];
void dfs(int x,int fa) {
int i,d,chd=0;
dp[x][1]=MAX;
dp[x][0]=son[x]=0;
for (i=u[x];i!=-1;i=pre[i])
if (v[i]!=fa) {
dfs(v[i],x);
d=(son[v[i]]&1) ? 1:2;
chd++;son[x]+=son[v[i]];
dp[x][0]+=dp[v[i]][0]+d;//偶数情况
}
for (i=u[x];i!=-1;i=pre[i])
if (v[i]!=fa) {//奇数情况从偶数情况中转换过来
if (chd>1&&son[v[i]]==1) dp[x][1]=min(dp[x][1],dp[x][0]);
if (dp[v[i]][1]==MAX) continue ;
d=(son[v[i]]&1) ? 1:-1;
dp[x][1]=min(dp[x][1],dp[x][0]-dp[v[i]][0]+dp[v[i]][1]+d);
}
if (!chd) son[x]=1;
}
int main()
{
int a,b,i,n,t,root,leaf;
scanf("%d", &t);
while (t--) {
scanf("%d", &n);
tot=root=leaf=0;
memset(d,0,sizeof(d));
memset(u,-1,sizeof(u));
for (i=1;i<n;i++) {
scanf("%d%d", &a, &b);
add(a,b);add(b,a);
d[a]++;d[b]++;
}
if (n==2) { printf("1\n");continue ; }
for (i=1;i<=n;i++)
if (d[i]!=1) root=i;
else leaf++;
dfs(root,0);
printf("%d\n", dp[root][leaf&1]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: