原题链接: http://codeforces.com/contest/1447/problem/B
测试样例
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
Note
In the first test case, there will always be at least one −1, so the answer is 2.
In the second test case, we can use the operation six times to elements adjacent horizontally and get all numbers to be non-negative. So the answer is: 2×1+3×2+3×3+2×4+1×5=30.
题意: 给你一个矩阵,你可以选择相邻的元素让它们都乘以。我们定义为矩阵的和,你需要通过操作使得最大。
解题思路: 由于操作次数不受限制,故我们总可以将矩阵中存在的负数变成个或个。(这与原矩阵中的负数数量有关,因为两个负数之间可以变成两个正数,异号则不行。)我们想要使得和最大,所以我们如果可以将所有的负数都变成个那自然和最大。如果只能让负数剩下一个,那么我们自然想使得这个负数的绝对值最小。 有了这个思路,我们自然可以去解决此问题,即遍历矩阵,统计矩阵的绝对值和和绝对值最小的那个数,同时我们需要统计负数的数量。这样即可得出答案。
AC代码
/*
*
*/
//POJ不支持
using namespace std;
const int inf=0x3f3f3f3f;//无穷大。
const int maxn=55;//限定值。
typedef long long ll;
int t,n,m;
int a[maxn][maxn];
int main(){
while(cin>>t){
while(t--){
int sum=0,minn=inf,cnt=0;
cin>>n>>m;
rep(i,0,n-1){
rep(j,0,m-1){
cin>>a[i][j];
minn=min(minn,abs(a[i][j]));
if(a[i][j]<0)cnt++;
sum+=abs(a[i][j]);
}
}
if(cnt%2){
cout<<sum-2*minn<<endl;
}
else{
cout<<sum<<endl;
}
}
}
return 0;
}