HDU1856 (More is better)-query set + tree

Source: Internet
Author: User

[Java]
Package D0813;
/*
* Questions: mr wang puts a group of children in a room. Some of these children are friends,
* Mr wang selects some children from the room each time and asks you at most a few children (the children must be friends,
* It can be either direct or inter-node), giving a direct friend relationship, and asking you to determine the number of children left most.
* Train of Thought: Check the set and find the result with the largest number of sets.
**/
Import java. io .*;
Public class HDU1856 {
Static int [] set;
Static int [] height;
Static int [] boy; // number of nodes.
Static int max;
Public static void main (String [] args) throws IOException {
StreamTokenizer st = new StreamTokenizer (new BufferedReader (new InputStreamReader (System. in )));
While (st. nextToken ()! = StreamTokenizer. TT_EOF ){
Int n = (int) st. nval;
Init (n );
Max = 1; // be sure to pay attention to this place. Do not set it to 0. Because at least one child can be left in the end.
For (int I = 0; I <n; I ++ ){
St. nextToken ();
Int s = (int) st. nval;
St. nextToken ();
Int e = (int) st. nval;
Merge (s, e );
}
System. out. println (max );
}
}
 
Public static void init (int n ){
Boy = new int [2 * n + 1];
Height = new int [2 * n + 1];
Set = new int [2 * n + 1];
For (int I = 1; I <= 2 * n; I ++ ){
Set [I] = I;
Height [I] = 1;
Boy [I] = 1;
}
}
Public static int find (int x ){
Int son, temp;
Son = x;
While (x! = Set [x])
X = set [x];
// Path compression, which can be left empty
While (son! = X ){
Temp = set [son];
Set [son] = x;
Son = temp;
}
Return x;
}
Public static void merge (int a, int B ){
A = find ();
B = find (B );
If (! = B ){
If (height [a]> height [B]) {
Set [B] =;
Boy [a] + = boy [B];
Max = Math. max (max, boy [a]);
}
Else if (height [a] Set [a] = B;
Boy [B] + = boy [a];
Max = Math. max (max, boy [B]);
}
Else {
Set [B] =;
Height [a] ++;
Boy [a] + = boy [B];
Max = Math. max (max, boy [a]);
}
}
}
}

 


Author; lhfight

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.