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(1≤ai≤n)
一个
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;
}