[BZOJ1131][POI2008]Sta
生活随笔
收集整理的這篇文章主要介紹了
[BZOJ1131][POI2008]Sta
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Description
給出一個(gè)N個(gè)點(diǎn)的樹,找出一個(gè)點(diǎn)來,以這個(gè)點(diǎn)為根的樹時(shí),所有點(diǎn)的深度之和最大
Input
給出一個(gè)數(shù)字N,代表有N個(gè)點(diǎn).N<=1000000 下面N-1條邊.
Output
輸出你所找到的點(diǎn),如果具有多個(gè)解,請(qǐng)輸出編號(hào)最小的那個(gè).
Sample Input
81 4
5 6
4 5
6 7
6 8
2 4
3 4
Sample Output
7Solution
做法:樹形$dp$
事實(shí)上樹形$dp$一遍之后以某個(gè)節(jié)點(diǎn)為根的情況就可以直接$O(1)$轉(zhuǎn)移了,所以直接做就好了
設(shè)$f[i]$表示以$i$為根的情況
$f[ son ] = f[ u ] + n - 2 * siz[ son ] $
#include <bits/stdc++.h>using namespace std ;#define ll long long #define N 2000010int ans = 0 , n ; int cnt , head[ N ] ; ll f[ N ] , siz[ N ] , dep[ N ] ; struct node {int to , nxt ; }e[ N ];void ins( int u , int v ) {e[ ++ cnt ].to = v ;e[ cnt ].nxt = head[ u ] ;head[ u ] = cnt ; }void dfs1( int u , int fa ) {siz[ u ] = 1 ;f[ u ] = dep[ u ] ;for( int i = head[ u ] ; i ; i = e[ i ].nxt ) {if( e[ i ].to == fa ) continue ;dep[ e[ i ].to ] = dep[ u ] + 1 ;dfs1( e[ i ].to , u ) ;siz[ u ] += siz[ e[ i ].to ] ;f[ u ] += f[ e[ i ].to ] ;} }void dfs2( int u , int fa ) {for( int i = head[ u ] ; i ; i = e[ i ].nxt ) {if( e[ i ].to == fa ) continue ;f[ e[ i ].to ] = f[ u ] + n - 2 * siz[ e[ i ].to ] ; dfs2( e[ i ].to , u ) ;} }int main() {scanf( "%d" , &n ) ;for( int i = 1 ; i < n ; i ++ ) {int x , y ;scanf( "%d%d" , &x , &y ) ;ins( x , y ) ;ins( y , x ) ;}dfs1( 1 , 0 ) ;dfs2( 1 , 0 ) ;for( int i = 1 ; i <= n ; i ++ ) {if( f[ i ] > f[ ans ] ) ans = i ;}printf( "%d\n" , ans ) ; }?
轉(zhuǎn)載于:https://www.cnblogs.com/henry-1202/p/BZOJ1131.html
總結(jié)
以上是生活随笔為你收集整理的[BZOJ1131][POI2008]Sta的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 牛客国庆集训派对Day2 F、平衡二叉树
- 下一篇: 擎科试剂盒eluent指的是depc水吗