codeforces 1029 E. Tree with Small Distances(樹形dp||貪心)

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;
 
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章