zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    列表框JList 及动作监听
    WindowListener(附带适配器改良方案)
    常用的几种文本组件(JTextComponent)
    JToggleButton组件
    java实现鼠标拖拽动作监听
    Flex读文本文件
    WPF socket通讯 UDP接收消息
    在线签名,并保存到本地
    flex直接访问服务器
    windows 8各种流之间的转换
  • 原文地址:https://www.cnblogs.com/yxg123123/p/6827672.html
Copyright © 2011-2022 走看看