Tourist tree dp

Subject: https://ac.nowcoder.com/acm/problem/15748
Cwbc and XHRlyb live in city s, and they plan to travel together on this day.

There are n cities on the travel map, and they are connected by n-1 roads.

Cwbc and XHRlyb will stay in city s on the first day and visit all the cities with a distance of no more than 1 from it. After that, they will choose a city to stay in every day, and then visit all the cities with a distance of no more than 1 from it.

They don't want to live in a city that they have already visited, and they want to extend their travel time as much as possible.

XHRlyb wants to know how many days she can spend with Cwbc at most?

After reading the question carefully, you will be able to solve this problem smoothly!

Input description: The
first line, two positive integers n and s, indicate the number of cities and the city s where you will stay on the first day.
In the next n-1 lines, each line contains two integers x and y, indicating that there is a two-way road between city x and city y.

Output description: In the
first line, a non-negative integer represents the answer.

Example 1

Input
Copy
4 1
1 2
2 3
3 4

Output
copy
2

Description

On the first day, we stayed in No. 1 city and visited No. 1 and 2 cities.
The next day, stayed in No. 3 city, visited No. 4 city, and the trip ended.

Remarks:
1 ≤ n ≤ 500000, 1 ≤ s, x, y ≤ n.

Problem solution, this is a tree-shaped dp introductory problem.
To maximize the number of days to travel, use dp, because as long as you live there must be one day, so all dp[u][1]=1. dp[u][0] represents the maximum number of days you can stay in city u, and dp[u][1] represents the maximum time you can stay in city u. Then because the adjacent node v must be 0 after u lives, so there is dp[u][1]+=dp[v][0], if u does not live, then the adjacent node v can live or not, then Just select the maximum value. When dp[u][0]+=max(dp[v][1],dp[v][0])
is used for dp using dfs at the same time, since the image is saved as a two-way graph, the parameters are passed in It is u, fa, if it is equal to the parent node, skip it.

Code:

#include <bits/stdc++.h>
#include <algorithm>
#include<iostream>
#include <stdio.h>
const int maxn=5e5+5;
using namespace std;
typedef long long ll;
vector<int>g[maxn];
int r[maxn];
int dp[maxn][2];//该节点选不选的最长时间
//int ans=0;
void dfs(int u,int fa){
    
    
    dp[u][1]=1;//只要选了必有一天
    for(int i=0;i<g[u].size();i++){
    
    
        int v=g[u][i];
        if(fa==v)
            continue;
        dfs(v,u);
        dp[u][1]+=dp[v][0];
        dp[u][0]+=max(dp[v][1],dp[v][0]);
    }
}

int main (){
    
    
    int n,s,x,y;
    cin>>n>>s;
    for(int i=1;i<n;i++){
    
    
        cin>>x>>y;
        g[x].push_back(y);
        g[y].push_back(x);
    }
    dfs(s,0);
    cout<<dp[s][1]<<endl;
    return 0;
}

Guess you like

Origin blog.csdn.net/u011612364/article/details/108609766