CF600D problem solution
The title literally means
Gives an undirected graph, this requirement is harmonious FIG harmony defines that if A to C (A <B <C) of a road, then the B to C is also a way. A data range is 2e5
Then we realized that if all the elements of a subset is continuous, then this subset is harmony, because the connected graph, any two points can be reached. If a subset of the elements is not continuous, then you certainly need to have a multiple paths or even go to another subset. The two examples given illustrate:
Then it becomes a question of how to deal with.
I use the disjoint-set, for the point of attachment, are incorporated into the small to the point, and then update the array maxx array size (size [i] is used to record the number i is set at this time, to record set maxx the maximum)
Then we can judge very pleasant, if maxx [i] - i + 1 == size [i], then that is the harmony of this collection, that is, do not need to connect to the outside edge.
Then for a condition is not satisfied how to deal with it?
Very simple traversal i + 1 to maxx [i], of the need to merge the incoming set of combined can, in this process, maxx [i] are always updated, the complexity of this idea is O (n), very elegant.
Finally put rookie Code
1 #include <stdio.h> 2 #include <algorithm> 3 using namespace std; 4 const int N = 2e5+10; 5 int fa[N], maxx[N], size[N]; 6 int find(int x) //并查集基本操作 7 { 8 if(x==fa[x]) return x; 9 return fa[x] = find(fa[x]); 10 } 11 int main() 12 { 13 int x, y, fx, fy; 14 int n, m, res = 0; 15 scanf("%d %d", &n, &m); 16 for(int i = 1; i <= n; i++) //并查集的初始化 17 { 18 fa[i] = i; 19 maxx[i] = i; 20 size[i] = 1; 21 } 22 for(int i = 1; i <= m; i++) 23 { 24 scanf("%d %d", &x, &y); 25 //判断 然后建里并查集 26 fx = find(x); fy = find(y); 27 if(fx < fy) 28 { 29 fa[fy] = fx; 30 size[fx] += size[fy]; 31 maxx[fx] = max(maxx[fx], maxx[fy]); 32 }else if(fy < fx){ 33 fa[fx] = fy; 34 size[fy] += size[fx]; 35 maxx[fy] =max (Maxx [FX], Maxx [FY]); 36 } 37 [ } 38 is for ( int I = . 1 ; I <= n-;) 39 { 40 IF (FA [I] == I) // this is determined not to be is a 41 { 42 // satisfies the condition 43 is IF (size [I] == Maxx [I] -i + . 1 ) + I = size [I]; 44 is the else { 45 // not satisfy the condition 46 is for ( int J = + I . 1 ; J <= Maxx [I]; J ++ ) 47 { 48 // dynamically updating answer ++ 49 IF (Find (J) =! I) 50 { 51 is FA [J] = I; 52 is size [I] + = size [J]; 53 is Maxx [I] = max ( Maxx [I], Maxx [J]); 54 is RES ++ ; 55 } 56 is } 57 is } 58 } 59 } 60 the printf ( " % D \ n- " , RES); 61 62 }