D - Harmonious Graph

Subject to the effect:

n points, m edges, two numbers and l r, l and r if connected, then for any value between l and r and l are connected to be a number. Q. minimum number of edges to be added for this purpose.

answer:

We must first find the current largest communication block that point, all that is smaller than the current point and this point must be connected to the point, if not connected, then add an edge, so we can use a mark to mark the current array current Unicom point is in the current block, as is not the case, and the point size is smaller than the maximum block size of the current link point, we have to add one side. It can be used to traverse the link block dfs

#include<bits/stdc++.h>
using namespace std;
const int N=2E5+7;
vector<int >ve[N];
int mark[N];
int s=0;
void dfs(int x){
    mark[x]=1;
    s=max(s,x);
    for(int i=0;i<ve[x].size();i++){
        int a=ve[x][i];
        if(!mark[a]) dfs(a);
    }
}
int main(){
    int n,m;
    cin>>n>>m;
    int x,y;
    for(int i=1;i<=m;i++) {
        cin>>x>>y;
        ve[x].push_back(y);
        ve[y].push_back(x);
    }
    int ans=0;
    for(int i=1;i<=n;i++){
        if(mark[i]) continue ;
        if(i<s){
            ve[i].push_back(s);
            ve[s].push_back(i);
            years ++ ;
        }
        dfs(i);
    }
    cout<<ans<<endl;
    return 0;
}

Too seconds it! ! ! !

Guess you like

Origin www.cnblogs.com/Accepting/p/11919810.html