题解:CF2094G Chimpanzini Bananini
mengnn
·
·
题解
转化题意
给 b 数组,求“酷炫值”。
"炫酷值"为 \sum_{i=1}^m b_i \cdot i。
有 3 种操作 s:
$s=2$ 时:将现数组完全反转(反转答案);
$s=3$ 时:将现数组末尾增加一个值为 $k$ 的项(改变答案)。
其次,重要限制:$1 \leq q \leq 2 \cdot 10^5$。所以暴力的 $O(n^2)$ 效率肯定会 TLE。
## 分析
因为要快速处理正反 push,所以不难想到用 deque 来模拟 $b$ 数组。
首先我们要先考虑最重要的 $s=2$ 情况,处理该情况可以用一个 $now$ 变量判断现数组的正反($now=0$ 时正,$now=1$ 时反)。
所以在处理 $s=2$ 情况时可以直接 `now=!now` 解决。
再考虑 $s=3$ 时,要在队头或队尾加入元素 $k$ 所以考虑分讨:
1. $now=0$(正)时:往队尾添加;
2. $now=1$(反)时:往队头添加。
我们用 $ans1$ 表示数组正序答案,$ans2$ 表示数组倒序答案,$cnt$ 表示现数组中所有数之和。
1. $now=0$(正)时:
$ans1$ 直接算贡献为 `k*q.size()`(`q.size()` 为加入 $k$ 后数组元素个数)。
$ans2$ 很明显可以直接加 $cnt$。
2. $now=1$(反)时:
易知,与 $now=0$ 时 $ans1$ 与 $ans2$ 的贡献互换;
$ans1$ 直接加 $cnt$。
$ans2$ 贡献为 `k*q.size()`。
故得 $s=3$ 时实现代码为:
```cpp
inline void solve(int k){
cnt+=k;
if (now){
q.push_front(k);
ans1+=cnt;
ans2+=k*(long long)q.size();
}else{
q.push_back(k);
ans1+=k*(long long)q.size();
ans2+=cnt;
}return ;
}
```
接下来是最复杂的 $s=1$ 的情况:
与 $s=3$ 时类似的分讨,算贡献。
```
inline void move(){
if (q.empty()) return ;
long long x=q.front(),y=q.back(),p=q.size();
if (now){
ans1-=s-p*x;
ans2-=p*x-s;
q.push_back((int)x);
q.pop_front();
}else{
ans1-=p*y-s;
ans2-=s-p*y;
q.push_front((int)y);
q.pop_back();
}return ;
}
```
## AC code:
```cpp
#include<bits/stdc++.h>
using namespace std;
int T,qu;
long long s,ans1,ans2;
bool now;
deque<int> q;
inline void move(){
if (q.empty()) return ;
long long x=q.front(),y=q.back(),p=q.size();
if (now){
ans1-=s-p*x;
ans2-=p*x-s;
q.push_back((int)x);
q.pop_front();
}else{
ans1-=p*y-s;
ans2-=s-p*y;
q.push_front((int)y);
q.pop_back();
}return ;
}
inline void solve(int x){
s+=x;
if (now){
q.push_front(x);
ans1+=s;
ans2+=x*(long long)q.size();
}else{
q.push_back(x);
ans1+=x*(long long)q.size();
ans2+=s;
}return ;
}
//这里因为习惯,设插入变量名为 x,这个 x 就是插入的 k 。
int main(){
scanf("%d",&T);
while (T--){
scanf("%d",&qu);
q.clear();
now=ans1=ans2=s=0;
while (qu--){
int opt;
scanf("%d",&opt);
if (opt==1) move();
if (opt==2) now=!now;
if (opt==3){
int x;cin>>x;
solve(x);
}
printf("%lld\n",now?ans2:ans1);
}
}
return 0;
}
```