• hihocoder #1224 : 赛车 dfs


    题目链接:

    http://hihocoder.com/problemset/problem/1224

    题意:

    题解:

    首先我们先dfs出最长链,然后我们再dfs出每一个点能够最长延展多少
    然后最后答案就是最长链的长度+最长延展多少就好了

    代码:

     1 #include <bits/stdc++.h>
     2 using namespace std;
     3 typedef long long ll;
     4 #define MS(a) memset(a,0,sizeof(a))
     5 #define MP make_pair
     6 #define PB push_back
     7 const int INF = 0x3f3f3f3f;
     8 const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
     9 inline ll read(){
    10     ll x=0,f=1;char ch=getchar();
    11     while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    12     while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    13     return x*f;
    14 }
    15 //////////////////////////////////////////////////////////////////////////
    16 const int maxn = 1e5+10;
    17 
    18 vector<int> G[maxn];
    19 int d[maxn],vis[maxn],fa[maxn];
    20 
    21 void dfs(int x,int deep){
    22     d[x] = deep;
    23     for(auto v : G[x]){
    24         if(vis[v]) continue;
    25 
    26         fa[v] = x;
    27         dfs(v,deep+1);
    28     }
    29 }
    30 
    31 int main(){
    32     int n=read();
    33     for(int i=1; i<n; i++){
    34         int u=read(),v=read();
    35         G[u].push_back(v);
    36     }
    37     dfs(1,0);
    38 
    39     int bf=1,ans1 = 0;
    40     for(int i=1; i<=n; i++){
    41         if(d[i] > ans1){
    42             ans1 = d[i];
    43             bf = i;
    44         }
    45     }
    46 
    47     while(bf != 1){
    48         vis[bf] = 1;
    49         bf = fa[bf];
    50     }
    51     vis[1] = 1;
    52 
    53     for(int i=1; i<=n; i++){
    54         if(vis[i])
    55             dfs(i,0);
    56     }
    57 
    58     int ans2 = 0;
    59     for(int i=1; i<=n; i++)
    60         if(!vis[i])
    61             ans2 = max(d[i],ans2);
    62 
    63     cout << ans1+ans2 << endl;
    64 
    65     return 0;
    66 }
  • 相关阅读:
    1009 Product of Polynomials (25分)
    VS code 调试C++
    1065 A+B and C (64bit) (20分)
    UML与数据库应用系统
    语句(switch,异常,NDEBUG,assert)
    1046 Shortest Distance (20分)
    1042 Shuffling Machine (20分)
    模块和包
    闭包&装饰器
    迭代器、生成器
  • 原文地址:https://www.cnblogs.com/yxg123123/p/6827672.html
Copyright © 2020-2023  润新知