E. Alice and the Unfair Game(dsu)

E. Alice and the Unfair Game

题意:

输入 n ( 1 e 5 ) , m ( 1 e 5 ) n(1e5),m(1e5) n(1e5),m(1e5)
接下来输入 a 1 , a 2 , … , a m ( 1 ≤ a i ≤ n ) a_1,a_2,\dots,a_m(1\leq a_i\leq n) a1,a2,,am(1ain)
一个 m + 1 m+1 m+1轮,最后一轮无限制条件,前 m m m个条件,每一轮位置可以不变,向左移一次,右移一次,对于第 i i i轮,不能移动到 a i a_i ai;求 ( s , t ) (s,t) (s,t)的对数, s s s起始位置, t t t结束位置。

题解:

对于每一个起始位置,终点位置的范围肯定的一对,对于每轮的限制条件dsu即可。
注意: n = 1 n=1 n=1时,答案为0;
优化: 只考虑大小,不用数组保存,这样复杂度就优化到 O ( m ) O(m) O(m),而dsu复杂度是 m log ⁡ ( n ) m\log(n) mlog(n),这里就没有优化了。

代码:

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+9;
map<int,vector<int>>l,r;
int n,m;
int a[N];
int main(){
  //  freopen("tt.in","r",stdin),freopen("tt.out","w",stdout);
    cin>>n>>m;
    for(int i=1;i<=m;i++)cin>>a[i];
    if(n==1){//注意
        if(m)cout<<0<<endl;
        else cout<<1<<endl;
        return 0;
    }
    for(int i=1;i<=n;i++)l[i].push_back(i),r[i].push_back(i);
    for(int i=1;i<=m;i++){
        int z=a[i]+i,y=a[i]-i;
        int tz=z+1,ty=y-1;
        if(l[tz].size()<l[z].size())swap(l[tz],l[z]);
        for(auto j:l[z])l[tz].push_back(j);l[z].clear();
        if(r[ty].size()<r[y].size())swap(r[ty],r[y]);
        for(auto j:r[y])r[ty].push_back(j);r[y].clear();
    }
    #define ll long long
    ll ans=n;
    for(auto i:l){
        int t=i.first-m-1;
        t=max(t,1);
        ans-=1ll*t*i.second.size();
    }
    for(auto i:r){
        int t=i.first+m+1;
        t=min(t,n);
        ans+=1ll*t*i.second.size();
    }
    cout<<ans<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值