蓝桥杯备考---》贪心算法之矩阵消除游戏

我们第一次想到的贪心策略一定是找出和最大的行或者列来删除,每次都更新行和列

比如如图这种情况,这种情况就不如直接删除两行的多,所以本贪心策略有误

so我们可以枚举选的行的情况,然后再贪心的选择列和最大的列来做

cpp 复制代码
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int n,m,k;
typedef long long ll;
const int N = 20;

int sum;

int col[N];
int a[N][N];


	int calc(int x)
{
 int ret = 0;
 while(x)
 {
 ret++;
 x -= x & -x; 
 }
 return ret;
}

bool cmp(int x,int y)
{
	return x>y;
}
int ret;

int main()
{
	cin >> n >> m >> k;
	for(int i = 0;i<n;i++)
	{
		for(int j = 0;j<m;j++)
		{
			cin >> a[i][j];
		}
	}
	for(int st = 0;st<(1<<n);st++)
	{
		memset(col,0,sizeof(col));
		sum = 0;
		if(calc(st)>k) continue;
		for(int i = 0;i<n;i++)
		{
			for(int j = 0;j<m;j++)
			{
				if((st>>i)&1) sum+=a[i][j];
				else col[j]+=a[i][j];
			}
		}
		sort(col,col+m,cmp);
		int tmp = k-calc(st);
		for(int i = 0;i<tmp;i++)
		{
			sum+=col[i];
		}
		ret = max(ret,sum);
		
	}
	cout << ret; 
	
	
	
	
	return 0;
}

这样写是有bug的,我们选列的时候有可能会越界

因为我们的k最高是n*m,假如不选行,全选列,列是不够选的啊,我们应该对col的遍历范围做点限制,不能超过m

正确代码√

cpp 复制代码
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int n,m,k;
typedef long long ll;
const int N = 20;
int a[N][N];
int sum;
int col[N];




	int calc(int x)
{
 int ret = 0;
 while(x)
 {
 ret++;
 x -= x & -x; 
 }
 return ret;
}

bool cmp(int x,int y)
{
	return x>y;
}
int ret;
int main()
{
	cin >> n >> m >> k;
	for(int i = 0;i<n;i++)
	{
		for(int j = 0;j<m;j++)
		{
			cin >> a[i][j];
		}
	}
	for(int st = 0;st<(1<<n);st++)
	{
		memset(col,0,sizeof(col));
		sum = 0;
		if(calc(st)>k) continue;
		for(int i = 0;i<n;i++)
		{
			for(int j = 0;j<m;j++)
			{
				if((st>>i)&1) sum+=a[i][j];
				else col[j]+=a[i][j];
			}
		}
		sort(col,col+m,cmp);
		int tmp = k-calc(st);
		for(int i = 0;i<min(tmp,m);i++)
		{
			sum+=col[i];
		}
		ret = max(ret,sum);
		
	}
	cout << ret; 
	
	
	
	
	return 0;
}
相关推荐
吃好睡好便好37 分钟前
提取矩阵某一行或某一列元素
开发语言·人工智能·线性代数·算法·matlab·矩阵
云泽8084 小时前
笔试算法 -位运算篇(二):从唯一字符到消失数字
c++·算法·位运算
ʚ希希ɞ ྀ4 小时前
不同路径|| -- dp
算法
IT 行者5 小时前
SimHash 与 MinHash:相似性计算的双子星算法
算法·hash·比对
智者知已应修善业6 小时前
【51单片机8位数码管动态显示日期小数点风格】2023-11-13
c++·经验分享·笔记·算法·51单片机
智者知已应修善业6 小时前
【51单片机有三个LED 分别第一个灯闪三下 再到第二个灯又闪三下 再到第三个灯又闪三下 就这样循环程序】2023-11-16
c++·经验分享·笔记·算法·51单片机
小L~~~7 小时前
基于贪心策略的混合遗传算法求解01背包问题
python·算法
charley.layabox8 小时前
大连理工,将 LayaAir AI 游戏设计带进校园
人工智能·游戏
洛水水8 小时前
【力扣100题】53.最长回文子串
算法·leetcode·职场和发展