题意:有一个 n*m的矩阵,其中元素有负有正,每次可选任意相邻的俩元素将它们的符号取反,可进行任意次操作,求出可实现的整个矩阵最大矩阵和。
思路:
- 既然可以任意次操作,那么如果负数为偶数个,直接俩俩一起取反,最后整个矩阵都会是正数。
- 若负数为奇数个,将负号留个绝对值最小的数即可。
代码实现:
#include<bits/stdc++.h>
#define endl '\n'
#define null NULL
#define ll long long
#define int long long
#define pii pair<int, int>
#define lowbit(x) (x &(-x))
#define ls(x) x<<1
#define rs(x) (x<<1+1)
#define me(ar) memset(ar, 0, sizeof ar)
#define mem(ar,num) memset(ar, num, sizeof ar)
#define rp(i, n) for(int i = 0, i < n; i ++)
#define rep(i, a, n) for(int i = a; i <= n; i ++)
#define pre(i, n, a) for(int i = n; i >= a; i --)
#define IOS ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);
const int way[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
using namespace std;
const int inf = 0x7fffffff;
const double PI = acos(-1.0);
const double eps = 1e-6;
const ll mod = 1e9 + 7;
const int N = 200;
int t, n, m;
int a[N][N];
signed main()
{
IOS;
cin >> t;
while(t --){
cin >> n >> m;
int f = 0, sum = 0, minn = inf;
for(int i = 1; i <= n; i ++){
for(int j = 1; j <= m; j ++){
cin >> a[i][j];
if(a[i][j] < 0) f ++;
sum += abs(a[i][j]);
minn = min(minn, abs(a[i][j]));
}
}
if(f%2) cout << sum-minn*2 << endl;
else cout << sum << endl;
}
return 0;
}