Main topic:
Defines the value of the tree as the number of point pairs in the diameter of a tree on a tree.
Given a tree, let you ask what is the maximum value of the tree formed by a connected sub-graph of the tree.
First, it can be thought that all the largest diameter of a tree must go through the same point, if there are two diameter does not intersect, then must be able to find a longer chain.
Furthermore, if this point of intersection is determined, the maximum depth of the subtree for all of this must be only one different or the same as the other.
Then we only use all the points as the intersection of the diameter, the number of each subtree each depth of how many points to deal with, and then calculate all the same situation.
But what if there's a difference? Enumeration diameter length recalculation will definitely time out. However, we can observe that if the length difference is more than 1, we can move the intersection to the deep subtrees tree, that is, when we calculate the root of the deep subtree, we calculate only 1 more of the same deep tree.
Code:
classTreediameters { Public: #defineMAXN 1005inthead[maxn],cnt; structedge{intTo,next; }E[MAXN*2]; InlinevoidInsertintAintb) {e[++cnt].next=head[a];head[a]=cnt;e[cnt].to=b; e[++cnt].next=head[b];head[b]=cnt;e[cnt].to=A; } intTOT[MAXN],DEP[MAXN][MAXN],ALL[MAXN]; voidDfsintSintVintFaintd) {Dep[s][d]++; for(intI=head[v];i;i=e[i].next)if(E[I].TO!=FA) DFS (s,e[i].to,v,d+1); } intAns,n; voidWorkintv) {memset (tot,0,sizeof(tot)); tot[0]=1; memset (All,0,sizeof(All)); for(intI=head[v];i;i=E[i].next) {memset (dep[e[i].to],0,sizeof(dep[e[i].to])); DFS (E[I].TO,E[I].TO,V,1); for(intj=1; j<=n;j++) {All[j]+=tot[j]*Dep[e[i].to][j]; TOT[J]+=Dep[e[i].to][j]; Ans=Max (ans,all[j]); } } for(intI=head[v];i;i=E[i].next) { for(intj=0; j<=n;j++) {ans=max (ans, (tot[j]-dep[e[i].to][j]) *dep[e[i].to][j+1]); } } } intGetmax (vector<int>p) {n=p.size (); ans=0; for(intI=0; i<n;i++) Insert (p[i],i+1); for(intI=0; i<=n;i++) work (i); returnans; }};
Tc--srm-703-div2-1000-treediameters