跳到正文

题解

题解:CF2104B Move to the End

TMXtmx20121001约 3 分钟
原文
文章信息与版本

文章信息

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

版本

  1. v1当前

这个题目显然不能用贪心或者排序技巧,因为数组每次都会回到原来的状态,那么最先想到的就是暴力模拟:

C++
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=200001;
#define I return
#define Love 0
#define Daimayuan ;
#define endl '\n'
#define ri register int
#define int long long

int t;
int n;

inline void work(){
	cin >> n;
	vector<int> a(n);
	for (int i=0;i<n;i++)
		cin >> a[i];
	for (int k=1;k<=n;k++){
		int ma=0;
		for (int i=0;i<n;i++){
			vector<int> b(n);
			for (int j=i;j<n-1;j++)
				b[j]=a[j+1];
			b[n-1]=a[i];
			int now=0;
			for (int j=0;j<k;j++)
				now+=b[n-j-1];
			ma=max(ma,now);
		}
		cout << ma << ' ';
	}
	cout << '\n';
}

signed main(){
	ios::sync_with_stdio(0);
	cin.tie(0);cout.tie(0);
	cin >> t;
	while (t--) work();
	I Love Daimayuan
}

不难看出,你会喜提TLE,所以说想要过这个题,要么优化,要么换思路。 看到要求和,又不难想到每次要往后挪一个最大值,那么就能用前缀和+前缀最大值。

C++
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=200001;
#define I return
#define Love 0
#define Daimayuan ;
#define endl '\n'
#define ri register int
#define int long long

int t;
int n,a[N],s[N],ma[N];

inline void work(){
	cin >> n;
	s[0]=0;
	for (int i=0;i<n;i++)
		cin >> a[i],s[i+1]=s[i]+a[i];
	ma[0]=a[0];
	for (int i=1;i<n;i++)
		ma[i]=max(ma[i-1],a[i]);
	for (int k=1;k<=n;k++){
		int l=n-k;
		int ch=s[n]-s[l];
		if (l==0)
			cout << ch << ' ';
		else
			cout << max(ch,ch-a[l]+ma[l-1]) << ' ';
	}
	cout << '\n';
}

signed main(){
	ios::sync_with_stdio(0);
	cin.tie(0);cout.tie(0);
	cin >> t;
	while (t--) work();
	I Love Daimayuan
}

下班,rp++

原文