Center of gravity of the poj1655balancing act Tree, tree DP

Source: Internet
Author: User

Poj1655

The first DFS calculates the number of nodes for each subtree.

Second DFS request answer

This is the foundation of poj1741 (Code 1741)

The same is true for poj3107. However, all vertices must be output, and STL (large data size) cannot be used.

# Include <iostream> # include <cstdio> # include <cstring> # include <vector> using namespace STD; int N; vector <int> son [20010]; // graph storage structure int vis [20010]; // indicates whether int num [20010] has been accessed; // The number of subtree nodes int DP [20010]; // Answer void dfs_num (int n) {int Len = Son [N]. size (); num [N] = 1; vis [N] = 1; for (INT I = 0; I <Len; I ++) {int K = Son [N] [I]; // son if (vis [k]) continue; dfs_num (k ); num [N] + = num [k];} // printf ("@ % d \ n", N, num [N]);} void dfs_node (int n, int from) {int K, Len = Son [N]. size (); vis [N] = 1; DP [N] = 0; For (INT I = 0; I <Len; I ++) {k = Son [N] [I]; If (vis [k]) {DP [N] = max (DP [N], n-num [N]);} else {DP [N] = max (DP [N], num [k]); dfs_node (k, n) ;}} int main () {int I, j, k, T, U, V; scanf ("% d", & T); While (t --) {scanf ("% d", & N ); for (I = 1; I <= N; I ++) Son [I]. clear (); memset (Num, 0, sizeof (Num); memset (DP, 0, sizeof (DP); for (I = 1; I <= N-1; I ++) {scanf ("% d", & U, & V); son [u]. push_back (V); son [v]. push_back (U);} memset (VIS, 0, sizeof (VIS); dfs_num (1); memset (VIS, 0, sizeof (VIS); dfs_node (1, -1); for (I = J = k = N; I> = 1; I --) {If (k> DP [I]) {k = DP [I]; j = I;} If (k = DP [I]) {J = I ;}} printf ("% d \ n", j, k );} return 0;}/* 272 61 21 44 53 73 1111 21 31 42 52 64 74 84 98 108 11 */

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.