"Academic article" oj.jzxx.net2701 Tree __.net

Source: Internet
Author: User

This is a question from Oierbbs.
Original post address: http://www.oierbbs.com/forum.php?mod=viewthread&tid=512?fromuid=71
(It seems to be a very small BBS.) Not from Los Valley Airborne at all. )

I can't endure the typesetting of the original post. The style of the topic has been processed again. ) Topic Description

The taste of the tree is very interesting recently, what is a tree. A tree is a non-loop connected undirected graph formed by n nodes and n-1 strips.
Taste in the research process to know, for a root-free tree, when the node I as the root of the height of the tree is how much. The so-called tree height refers to from the root node, to the root node farthest leaves node through the total number of nodes, see the input and Output sample 1. Taste taste now encountered some things, do not want to continue to think, please help her solve this problem. Input Format

Enter a total of n rows.
1th behavior a positive integer n that represents the number of nodes in the tree.
Line 2nd to n rows, two positive integers a and b separated by spaces, indicating A and B have a hyphen. output Format

The output is a total of n rows, and row I represents the height of the tree when node I is the root. Sample Input

Sample 1:
3
1 2
2 3
Sample 2:
4
1 4
2 4
3 4
Sample output
Sample 1:
3
2
3
Sample 2:
3
3
3
2

Data range (listen to LZ said): For 100% of the data, 1<=n<=1000
However I think the range of data: should be 1<=n<=5000000 (forcibly unkind)

(However, this layout is still very ugly) (escape
Source: Oj.jzxx.net (the original LZ did not give a question. _ (: З"∠) _ so went to the OJ. It should be 2701. )
Topic Transmission Gate: http://oj.jzxx.net/problem.php?id=2701
I can't use this OJ ... I'm so stupid, really.

Practices in the discussion area:
Law 1. Violence enumerates each point as the root, searching for the maximum depth of the tree (complexity: O (n^2))
Law 2. Balance tree. (Actually I do not know can, in fact, I do not understand, but should be able) (complexity: NLOGN)
Law 3. Split block (this looks pretty good.) Programming complexity lower than above) (complexity: O (n^1.5))

========================== I'm an academic dividing line ========================== topic

Given a tree with no root tree, the tree height of a tree with each point as root is obtained. Topic Analysis

Oh. This is not the equivalent of finding the maximum distance from each point on the tree to the other point on the tree.
This uses a knowledge point: The tree from the point to the tree diameter (*) One of the endpoints of the farthest distance ~ ~
*: Diameter: The diameter of the tree refers to the longest simple road of the tree.

So...... This problem has been finished. (Escape

First, the diameter, and then from the two ends of the diameter BFS, for the two distance to obtain the maximum can be ... diameter how to ask.

two times BFS. First pick a point to do the beginning BFS find the point from which the largest distance, and then from that point to BFS, then this BFS found the longest road is the diameter of the tree (that is, the most distance to find the point is the diameter of the other endpoint)

Principle: Set the starting point for U, the first bfs to find the endpoint v must be an endpoint of the diameter of the tree (according to a knowledge point), and then BFS find another endpoint is obviously ...

Then the two endpoints of the diameter are BFS to traverse the tree, update the distance of each node, then take the maximum from two distances.

Careful you must have found that the second time in the diameter of the BFS has been from an endpoint of the diameter, we can go with the update on the path of the value, so we are missing again BFS, this is really happy O (∩_∩) o

so,obviously, after the above steps, we have been answered.
of complexity. 3 times BFS, all O (M), because it is a tree, and the side is not, m= (n-1) * 2, so also 6 * (n-1) Bar
Total complexity: O (n) level (linear)

Perfect ~ ~ Code Implementation

STL code for heavy dependency. (Don't ask me why these three bfs look hot)

#include <queue> #include <cstdio> #include <cstring> using Std::vector;

Using Std::queue;
#define GC GetChar () #define CL (a,b) memset (A,b,sizeof (a)) const int n=1008;
Vector<int> E[n];

Queue<int> Q;

int d[n],_d[n];
    inline int gnum () {int A=0;char c=gc;bool f=0; for (;(c< ' 0 ' | |
    C> ' 9 ') &&c!= '-'; C=GC;
    if (c== '-') F=1,C=GC;
    for (; c>= ' 0 ' &&c<= ' 9 '; c=gc) a= (a<<1) + (a<<3) +c-' 0 '; if (f) return ~a+1;
return A;
    int BFS1 () {//Find an Endpoint cl (d,-1); d[1]=0 int mi=1; Q.push (1);
        while (!q.empty ()) {int X=q.front (); Q.pop ();
            for (int i=0;i<e[x].size (); i++) {int y=e[x][i];
                if (d[y]<0) {d[y]=d[x]+1; mi=y; Q.push (y);
Because it is a tree-shaped structure, so do not need to be like a real shortest path to add judgment, once the search must be the farthest (one)}} return mi;
    int BFS2 (int s) {//Find another endpoint, update the distance from this endpoint cl (d,-1); d[s]=1 int mi=s; Q.push (s); while (!q.empty ()) {int X=q.front (); Q.pop ();
        for (int i=0;i<e[x].size (); i++) {int y=e[x][i];
            if (d[y]<0) {d[y]=d[x]+1; mi=y; Q.push (y);
}} return mi;
    } void Bfs3 (int s) {//update distance from another endpoint cl (_d,-1); _d[s]=1 Q.push (s);
        while (!q.empty ()) {int X=q.front (); Q.pop ();
            for (int i=0;i<e[x].size (); i++) {int y=e[x][i];
                if (_d[y]<0) {_d[y]=_d[x]+1; Q.push (y);
                if (_d[y]>d[y]) d[y]=_d[y]; Lazy ing.
                If the distance is greater than the distance from the other end, cover it directly.
            Anyway, the tree-shaped structure will only run once a point.
    int main () {int n=gnum ()}}}
        for (int i=1;i<n;i++) {int u=gnum (), V=gnum ();
        E[u].push_back (v);
    E[v].push_back (U);
    int X=BFS1 (); int y=bfs2 (x); Bfs3 (y);
for (int i=1;i<=n;i++) printf ("%d\n", D[i]); //The question is really very simple.
It 's written in the back .

Basically this is the case, the following for the studious you are attached to a certain diameter of the way the correctness of the proof:
Proof: 1 if u is a point on the diameter, then V is obviously the end of the diameter (because if V is not, there must be another point w to make u to W distance longer, then in BFs found v contradiction)
2 if u is not a point on the diameter, then u to V is bound to intersect the diameter of the tree (disprove), then the intersection to V must be the second half of the diameter.
So v must be an endpoint of the diameter, so the BFS from V must be the diameter length

In fact, the most important thing is to understand some wonderful knowledge.

The end.

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.