NC15748 旅遊(樹形DP)

題目鏈接

題意:
nn1地圖有n個城市,n-1條邊
ss1第一天住在s點,把距離s爲1的城市遍歷一遍
1之後每一天選一個地方住,遍歷距離爲1的城市
但是每次遍歷過的城市不再去住
問最多能瀏覽幾天
題解:
nn1n個點,n-1條邊很明顯這是一棵樹
1由於每個點是否能住取決於他距離爲1的點是否住過
dp所以就可以考慮樹形dp
ss由於第一天住的是s,所以以s爲根節點
u宿宿對點u如果住宿最多可以留幾天,不住宿最多可以留幾天
dp由於是樹形dp,所以從下往上看
u宿宿如果選擇u住宿,那麼它的子節點一定不能住宿
u宿宿宿如果u不住宿,它的子節點可以任意選擇住宿或者不住宿,選擇最大值
ss宿dp所以最終推到根節點s,取出s住宿的情況的dp值
AC代碼

/*
    Author:zzugzx
    Lang:C++
    Blog:blog.csdn.net/qq_43756519
*/
#include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define endl '\n'
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int mod=1e9+7;
//const int mod=998244353;
const double eps = 1e-10;
const double pi=acos(-1.0);
const int maxn=1e6+10;
const ll inf=0x3f3f3f3f;
const int dir[4][2]={{0,1},{1,0},{0,-1},{-1,0}};

int dp[maxn][2];
vector<int> g[maxn];
void dfs(int u,int fa){
    dp[u][1]=1;
    for(auto v:g[u]){
        if(v==fa)continue;
        dfs(v,u);
        dp[u][1]+=dp[v][0];
        dp[u][0]+=max(dp[v][1],dp[v][0]);
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    int n,s;
    cin>>n>>s;
    for(int i=1,u,v;i<n;i++){
        cin>>u>>v;
        g[u].pb(v);
        g[v].pb(u);
    }
    dfs(s,0);
    cout<<dp[s][1]<<endl;
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章