Test instructions
Give a tree of n points and find a point to make the sum of the depths of all points of the tree with this point as the root;
n<=1000000;
Exercises
In fact, when I do this problem, there is always a kind of inexplicable sense of what is going on ...
Well, maybe I really did this problem ...
The more violent is the enumeration of all points, and then deep search to accumulate all depth;
But obviously all points are equal to the points of the parent tree + the sub-tree;
So just ask for the two to accumulate;
The total depth of the subtree is simply good, which is to +size the total depth of the son;
The parent tree is a little bit troublesome because it requires some preprocessing so in the second deep search solution;
For a point, the parent tree of this point is "Father + Father's parent tree + brother's subtree";
Then the separate accumulation can be:
Note that the formula is good; (plus minus the same item, don't go away.) It can't be adjusted. )
Time complexity O (n)
So just a tree-shaped DP silly question I still made a bunch of stupid mistakes;
1 million as 100,000, the formula is wrong, int output%LLD, update not sentenced to equal.
To this question also to open long long, this estimate is the only thing that I didn't fall into the pit = =;
Code:
#include <stdio.h> #include <string.h> #include <algorithm> #define N 1100000using namespace std; typedef long LONG Ll;int n,no,to[n<<1],next[n<<1],head[n],ce;ll sum[n],size[n],fas[n],ans;void Add (int x, int y) {to[++ce]=y;next[ce]=head[x];head[x]=ce;} void dfs1 (int x,int pre) {Size[x]=1;int i,y;for (I=head[x];i;i=next[i]) {if ((Y=to[i])!=pre) {DFS1 (y,x); size[x]+=size[y ];sum[x]+=sum[y]+size[y];}}} void dfs2 (int x,int pre) {int i,y;if (x!=1) fas[x]=fas[pre]+sum[pre]-sum[x]-size[x]+size[pre]-size[x]-1+n-size[pre]+1 ; if (Ans<fas[x]+sum[x]) {ans=fas[x]+sum[x];no=x;} else if (Ans==fas[x]+sum[x]) no=min (no,x); for (I=head[x];i;i=next[i]) {if ((y=to[i))!=pre) {DFS2 (y,x);}}} int main () {int m,i,j,k,x,y;scanf ("%d", &n), for (i=1;i<n;i++) {scanf ("%d%d", &x,&y), add (x, y), add (y,x);} DFS1 (1,0);d fs2 (1,0);p rintf ("%d\n", no); return 0;}
bzoj-1131 Sta