跳到正文

题解

题解:CF2094G Chimpanzini Bananini

mengnn约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 4 分钟
题目
CF2094G

版本

  1. v1当前

转化题意

给 bb 数组,求“酷炫值”。

“炫酷值”为 ∑i=1mbi⋅i\sum_{i=1}^m b_i \cdot i。

有 33 种操作 ss:

s=1s=1 时:将现数组末项移到首项位置(改变答案);

s=2s=2 时:将现数组完全反转(反转答案);

s=3s=3 时:将现数组末尾增加一个值为 kk 的项(改变答案)。

其次,重要限制:1≤q≤2⋅1051 \leq q \leq 2 \cdot 10^5。所以暴力的 O(n2)O(n^2) 效率肯定会 TLE。

分析

因为要快速处理正反 push,所以不难想到用 deque 来模拟 bb 数组。

首先我们要先考虑最重要的 s=2s=2 情况,处理该情况可以用一个 nownow 变量判断现数组的正反(now=0now=0 时正,now=1now=1 时反)。

所以在处理 s=2s=2 情况时可以直接 now=!now 解决。

再考虑 s=3s=3 时,要在队头或队尾加入元素 kk 所以考虑分讨:

  1. now=0now=0(正)时:往队尾添加;
  2. now=1now=1(反)时:往队头添加。

我们用 ans1ans1 表示数组正序答案,ans2ans2 表示数组倒序答案,cntcnt 表示现数组中所有数之和。

  1. now=0now=0(正)时:

ans1ans1 直接算贡献为 k*q.size()(q.size() 为加入 kk 后数组元素个数)。

ans2ans2 很明显可以直接加 cntcnt。

  1. now=1now=1(反)时:

易知,与 now=0now=0 时 ans1ans1 与 ans2ans2 的贡献互换;

ans1ans1 直接加 cntcnt。

ans2ans2 贡献为 k*q.size()。

故得 s=3s=3 时实现代码为:

C++
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=1s=1 的情况:

与 s=3s=3 时类似的分讨,算贡献。

C++
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:

C++
#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;
}
原文