首页 > 编程语言 >J Tokitsukaze and Sum of MxAb【2023牛客寒假算法基础集训营2】

J Tokitsukaze and Sum of MxAb【2023牛客寒假算法基础集训营2】

时间:2023-01-18 21:33:07浏览次数:63  
标签:集训营 Tokitsukaze int max Sum 负数 牛客 正数

J Tokitsukaze and Sum of MxAb

原题链接

题意

  • 给出长为n的序列,对于所有的i,j求max\((|a_i - a_j|,|a_i + a_j|)\)之和

思路

  1. 对于两个负数\(a_i\)和\(a_j\),max\((|a_i - a_j|,|a_i + a_j|) = -a_i - a_j\);
  2. 对于两个正数\(a_i\)和\(a_j\),max\((|a_i - a_j|,|a_i + a_j|) = a_i + a_j\);
  3. 对于一个正数\(a_i\)和一个负数\(a_j\),max\((|a_i - a_j|,|a_i + a_j|) = a_i - a_j\);
  4. 综上,可以得出负数都变为了正数,且求max\((|a_i - a_j|,|a_i + a_j|)\)之和的过程中每个数被计算了2n次,可以将问题转化为,将负数转化为正数后求2n个前缀和

代码

点击查看代码
#include<algorithm>
#include<iostream>
using namespace std;

#define prep(i,a,b) for(int i = (a); i <= (b); i ++)
#define rrep(i,a,b) for(int i = (a); i >= (b); i --)

typedef long long LL;
const char nl = '\n';
int T, n, m;
const int N = 1e5 + 10;
LL a[N];	//注意求和的数据范围

void solve() {
	res = 0;
	cin >> n;
	prep(i,1,n){
		cin >> a[i];
		if(a[i] < 0)a[i] *= (-1);
		a[i] += a[i - 1];
	}

	cout << 2*n*a[n] << nl;

}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0), cout.tie(0);
	cin >> T;
	while (T--) {
		solve();
	}
	return 0;
}

标签:集训营,Tokitsukaze,int,max,Sum,负数,牛客,正数
From: https://www.cnblogs.com/J-12045/p/17060613.html

相关文章