http://codeforces.com/contest/1029/problem/E
题意:给出以1位根节点有n个顶点,n-1条边的树,现在要添加边满足,1到所有顶点距离小于2
思路:考虑最优的的添加一定是直接与1节点相连,那么如何让添加一条边影响更多的点呢,考虑倒着做,如果叶子节点距离大于2,最优添加方式一定是将其父节点连接到1上,一定比直接添加到叶子节点上影响的点更多,那么只需要树形dp,先搜索子节点,子节点距离大于2,将该节点距离修改为1,将其父节点修改为2,继续往上回溯,这样贪心得到的答案一定最优
#include<bits/stdc++.h>
#include<tr1/unordered_map>
#define fi first
#define se second
#define show(a) cout<<a<<endl;
#define show2(a,b) cout<<a<<" "<<b<<endl;
#define show3(a,b,c) cout<<a<<" "<<b<<" "<<c<<endl;
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))
using namespace std;
typedef long long ll;
typedef pair<ll, ll> P;
typedef pair<P, int> LP;
const int inf = 0x3f3f3f3f;
const int N = 1e6 + 100;
const ll mod = 1e18+7;
const int base=131;
inline ll mul(ll x,ll y) { return (x*y-(ll)((long double)x*y/mod)*mod+mod)%mod;}
inline ll ksm(ll a,ll b) {ll ans=1;while(b){if(b&1)ans=mul(ans,a);a=mul(a,a),b>>=1;}return ans;}
ll n,m,x,y;
ll a[N];
ll k,ans,cnt;
ll res[N],num[N],vis[N];
ll pos[N];
vector<int> v[N];
map<P,ll> mp;
void dfs(int x,int dep,int fa)
{
int flag=0;
num[x]=dep;
for(int to:v[x])
{
if(to==fa) continue;
dfs(to,dep+1,x);
if(num[to]>2)
{
flag=1;
num[x]=1;
if(!num[fa]) num[fa]=2;
else num[fa]=min(num[fa],2ll);//注意父节点可能在另一个子树搜索中先被改成了1
}
}
if(flag) ans++;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin>>n;
for(int i=1;i<n;i++)
{
cin>>x>>y;
v[x].push_back(y);
v[y].push_back(x);
}
dfs(1,0,-1);
cout<<ans;
}