Yaroslav and Sequence - CodeForces 301A 水题

本文详细介绍了Yaroslav如何通过改变数组中特定数量的元素符号来最大化数组元素之和的问题解决方案。包括输入输出格式、样例解析及AC代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A. Yaroslav and Sequence
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Yaroslav has an array, consisting of (2·n - 1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1.

Yaroslav is now wondering: what maximum sum of array elements can be obtained if it is allowed to perform any number of described operations?

Help Yaroslav.

Input

The first line contains an integer n (2 ≤ n ≤ 100). The second line contains (2·n - 1) integers — the array elements. The array elements do not exceed 1000 in their absolute value.

Output

In a single line print the answer to the problem — the maximum sum that Yaroslav can get.

Sample test(s)
input
2
50 50 50
output
150
input
2
-1 -100 -1
output
100
Note

In the first sample you do not need to change anything. The sum of elements equals 150.

In the second sample you need to change the sign of the first two elements. Then we get the sum of the elements equal to 100.


思路:其实每次可以把任意两个的符号改变,那么就要考虑n是奇数还是偶数了,如果n是奇数(或n是偶数且其中有偶数个负数),那么可以让所有数变成非负数,如果n是偶数且有奇数个负数,那么必须剩一个负数。另外考虑有0的情况。

AC代码如下:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<vector>
using namespace std;
vector <int> vc1,vc2;
void solve()
{ int T,t,n,m,i,j,k,len1,len2,sum=0,ret,num0=0;
  scanf("%d",&n);
  for(i=1;i<=n*2-1;i++)
  { scanf("%d",&k);
    if(k>0)
     vc1.push_back(k);
    else if(k<0)
     vc2.push_back(k);
    else
     num0++;
  }
  len1=vc1.size();
  len2=vc2.size();
  for(i=0;i<len1;i++)
   sum+=vc1[i];
  for(i=0;i<len2;i++)
   sum-=vc2[i];
  if(num0>0 || len1==n*2-1 || n&1)
  { printf("%d\n",sum);
    return;
  }
  if(n%2==0 && len2%2==0)
  { printf("%d\n",sum);
    return;
  }
  ret=100000;
  for(i=0;i<len1;i++)
   ret=min(ret,vc1[i]);
  for(i=0;i<len2;i++)
   ret=min(ret,-vc2[i]);
  printf("%d\n",sum-2*ret);
}
int main()
{ solve();
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值