链式并查集合并+维护区间和

用于解决区间合并查询问题
https://ac.nowcoder.com/acm/contest/93847/E

#include<bits/stdc++.h>
#define endl '\n'
#define int long long
#define lowbit(x) (x&-x)
using namespace std;
const double pi=acos(-1);
const int N=2e5+5;
int fa[N],len[N],sum[N];

int find(int x){
    if(fa[x]==x) return x;
    else {
        return fa[x]=find(fa[x]);
    }
}
void join(int u,int v){
	u=find(u);
	v=find(v);
    if(u==v) return;
    if(u<v) swap(u,v);//向右边合并
    sum[u]+=sum[v];
    len[u]+=len[v];
    fa[v]=u;
}

void solve(){
	int n,m;cin>>n>>m;
    for(int i=1;i<=n;i++){
        cin>>sum[i];
        fa[i]=i;
        len[i]=1;
    }
    while(m--){
        int op;cin>>op;
        if(op==1){
            int l,r;cin>>l>>r;
            //区间合并
            while(l<r){
                join(l,l+1);
                l=find(l);
            }
        }
        else if(op==2){
            int t;cin>>t;
            t=find(t);
            double ans=(double)sum[t]/(double)len[t];
            
            printf("%.12lf\n",ans);
        }
    }
    
}
signed main(){
	ios::sync_with_stdio(false); cin.tie(nullptr);
	int t=1;
	//cin>>t;
	while(t--) solve();
	return 0;
}

posted on 2024-11-04 20:15  TaopiTTT  阅读(4)  评论(0编辑  收藏  举报