B. Numbers Box(基础贪心题)Codeforces Round #683 (Div. 2, by Meet IT)

原题链接: 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.

题意: 给你一个矩阵,你可以选择相邻的元素让它们都乘以 ( − 1 ) (-1) (1)。我们定义 X X X为矩阵的和,你需要通过操作使得 X X X最大。

解题思路: 由于操作次数不受限制,故我们总可以将矩阵中存在的负数变成 0 0 0个或 1 1 1个。(这与原矩阵中的负数数量有关,因为两个负数之间可以变成两个正数,异号则不行。)我们想要使得和最大,所以我们如果可以将所有的负数都变成 0 0 0个那自然和最大。如果只能让负数剩下一个,那么我们自然想使得这个负数的绝对值最小。 有了这个思路,我们自然可以去解决此问题,即遍历矩阵,统计矩阵的绝对值和和绝对值最小的那个数,同时我们需要统计负数的数量。这样即可得出答案。

AC代码

/*
*邮箱:unique_powerhouse@qq.com
*blog:https://me.csdn.net/hzf0701
*注:文章若有任何问题请私信我或评论区留言,谢谢支持。
*
*/
#include<bits/stdc++.h>//POJ不支持

#define rep(i,a,n) for(int i=a;i<=n;i++)
#define per(i,a,n) for(int i=a;i>=n;i--)

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;
}
posted @   unique_pursuit  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示