codeforces 1029 E. Tree with Small Distances(树形dp||贪心)

10 篇文章 0 订阅

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;
 
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值