https://ac.nowcoder.com/acm/contest/888/E
题意:给你一个无向图,其中每条边都有限制的大小区间可以通过,询问从1到n总共有多少个数字可以通过(即从1到n)
题解:由于m的范围很大,所以我不能单纯的跑图,所以我们可以用时间分治的思想,先把每个区间离散化,然后加入线段树中,然后跑线段树,跑的过程做并查集(即将相连的边归为一类)然后就可以查询答案了,跑完一个子树后,要把子树的并查集还原,不然会影响其他不同的区间的答案(并查集也要优化下,即连向最多有最多入度的类结点)
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int>P;
const int maxn = 1e5+9;
struct rt{
int u,v,l,r;
}arr[maxn];
int h[maxn<<2];
int mp[maxn<<2];
vector<P>dat[maxn<<2];
vector<int>s[maxn<<2];
int f[maxn<<1];
int ans=0;
int n,m;
int siz[maxn<<2];
int Find(int x){
while(x!=f[x]){
x=f[x];
}
return x;
}
void Union(int k,int x,int y){
x=Find(x);y=Find(y);
if(x==y)return;
if(siz[x]>siz[y])swap(x,y);
f[x]=y;
siz[y]++;
s[k].push_back(x);
}
void solve(int k){
for(int i=0;i<dat[k].size();i++){
Union(k,dat[k][i].first,dat[k][i].second);
}
}
void del(int k){
for(int i=0;i<s[k].size();i++){
f[s[k][i]]=s[k][i];
}
}
void dfs(int l,int r,int k){
solve(k);
if(l==r){
if(Find(1)==Find(n)){
// cout<<"r+1 "<<mp[r+1]<<" "<<"l "<<mp[l]<<endl;
// cout<<mp[r+1]-mp[l]<<endl;
ans+=mp[r+1]-mp[l];
}
del(k);
return;
}
int mid=(l+r)>>1;
dfs(l,mid,k<<1);
dfs(mid+1,r,k<<1|1);
del(k);
}
void updata(int a,int b,int l,int r,int k,int u,int v){
if(a<=l&&r<=b){
dat[k].push_back(P(u,v));
return;
}
int mid=(l+r)>>1;
if(a<=mid)updata(a,b,l,mid,k<<1,u,v);
if(b>mid)updata(a,b,mid+1,r,k<<1|1,u,v);
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)f[i]=i;
int tot=0;
for(int i=1;i<=m;i++){
scanf("%d%d%d%d",&arr[i].u,&arr[i].v,&arr[i].l,&arr[i].r);
h[tot++]=arr[i].l;
h[tot++]=arr[i].r+1;
}
sort(h,h+tot);
int num=unique(h,h+tot)-h;
for(int i=0;i<num;i++){
mp[i+1]=h[i];
}
for(int i=1;i<=m;i++){
int l=lower_bound(h,h+num,arr[i].l)-h+1;
int r=lower_bound(h,h+num,arr[i].r+1)-h+1;
updata(l,r-1,1,num-1,1,arr[i].u,arr[i].v);
}
dfs(1,num-1,1);
printf("%d\n",ans);
return 0;
}