日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Harmonious Graph CodeForces - 1253D(思维+并查集)

發布時間:2023/12/15 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Harmonious Graph CodeForces - 1253D(思维+并查集) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

You’re given an undirected graph with n nodes and m edges. Nodes are numbered from 1 to n.

The graph is considered harmonious if and only if the following property holds:

For every triple of integers (l,m,r) such that 1≤l<m<r≤n, if there exists a path going from node l to node r, then there exists a path going from node l to node m.
In other words, in a harmonious graph, if from a node l we can reach a node r through edges (l<r), then we should able to reach nodes (l+1),(l+2),…,(r?1) too.

What is the minimum number of edges we need to add to make the graph harmonious?

Input
The first line contains two integers n and m (3≤n≤200 000 and 1≤m≤200 000).

The i-th of the next m lines contains two integers ui and vi (1≤ui,vi≤n, ui≠vi), that mean that there’s an edge between nodes u and v.

It is guaranteed that the given graph is simple (there is no self-loop, and there is at most one edge between every pair of nodes).

Output
Print the minimum number of edges we have to add to the graph to make it harmonious.

Examples
Input
14 8
1 2
2 7
3 4
6 3
5 7
3 8
6 8
11 12
Output
1
Input
200000 3
7 9
9 8
4 5
Output
0
Note
In the first example, the given graph is not harmonious (for instance, 1<6<7, node 1 can reach node 7 through the path 1→2→7, but node 1 can’t reach node 6). However adding the edge (2,4) is sufficient to make it harmonious.

In the second example, the given graph is already harmonious.
思路:我們利用并查集把相連通的點鏈接到一個集合內,祖先為最大的那個點。然后我們從1開始查找,設置_max為最大祖先,如果i<_max內出現了getf(i)!=_max的情況,就需要增加一條邊了,然后將兩個集合合并,最大祖先更新。
代碼如下:

#include<bits/stdc++.h> #define ll long long using namespace std;const int maxx=2e5+100; int f[maxx]; int n,m;inline void init() {for(int i=0;i<=n+1;i++) f[i]=i; } inline int getf(int u) {return u==f[u]?u:f[u]=getf(f[u]); } inline void merge(int u,int v) {int t1=getf(u);int t2=getf(v);if(t1!=t2){if(t1>t2) f[t2]=t1;else f[t1]=t2;} } int main() {scanf("%d%d",&n,&m);init();int x,y;while(m--){scanf("%d%d",&x,&y);merge(x,y);}int ans=0;int _max=getf(1),tmp;for(int i=2;i<=n;i++){if(i<=_max){tmp=getf(i);if(tmp!=_max){merge(_max,tmp);_max=max(_max,tmp);ans++;}}else _max=getf(i);}cout<<ans<<endl;return 0; }

努力加油a啊,(o)/~

總結

以上是生活随笔為你收集整理的Harmonious Graph CodeForces - 1253D(思维+并查集)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。