Input
2
2 2
-1 1
1 1
3 4
0 -1 -2 -3
-1 -2 -3 -4
-2 -3 -4 -5
Output
2
30
思路
题目要求变换使得矩阵的和最大,由于变换次数不限,所以推断可知当负数数量为偶时,一定可以将所有值都变换为正数,此时结果为所有数的绝对值之和。当负数数量为奇时,至少会有一个数仍为负数,所以此时的结果为所有数的绝对值之和减去绝对值最小的数的两倍。
代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
ll k,m,n,r,t,x,y,ans,cnt,len,res,sum,tmp,a[500][500];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
cin>>t;
while(t--)
{
cnt=0;
sum=0;
tmp=inf;
cin>>n>>m;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cin>>a[i][j];
if(a[i][j]<0)
cnt++;
sum+=abs(a[i][j]);
tmp=min(tmp,abs(a[i][j]));
}
}
if(cnt%2!=0)
sum-=2*tmp;
cout<<sum<<endl;
}
return 0;
}