bzoj4165 矩阵 堆

25 篇文章 0 订阅
14 篇文章 0 订阅

Description


定义和谐矩阵为长不小于 Mina 且宽不小于 Minb 的矩阵,矩阵的权值为整个矩阵内所有数的和。给定一个长为 N
,宽为 M 的矩阵 A,求它的所有和谐子矩阵中权值第 K 小的矩阵,并输出它的权值。
Input
第 1 行为五个正整数,分别为 N , M , Mina , Minb , K,相邻两个数用一个空格分隔。接下来的 N 行,每行 M
个用一个空格分隔的数,表示给定的矩阵 A。
1 <= N,M <=1000, 1 <= Mina <= N, 1 <= Minb <= M,
1 <= K <= 250000 ,矩阵 A 内每个数均为不超过 3000 的非负整数

Solution


大水题~
我们把所有最小矩阵扔进堆里,每次取堆顶更新即可
由于我并不会奇怪的判重,因此用了set,导致时间比较挫

Code


#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#include <set>
#define rep(i,st,ed) for (register int i=st;i<=ed;++i)

typedef unsigned int LL;
const int N=3005;

LL s[N][N];

struct data {
	int x1,y1,x2,y2; LL sum;

	bool operator <(data b) const {
		data a=*this;
		if (a.sum!=b.sum) return a.sum<b.sum;
		if (a.x1!=b.x1) return a.x1<b.x1;
		if (a.y1!=b.y1) return a.y1<b.y1;
		if (a.x2!=b.x2) return a.x2<b.x2;
		if (a.y2!=b.y2) return a.y2<b.y2;
		return false;
	}
} top,tmp;

std:: set <data> heap;

void get_sum(data &a) {
	a.sum=s[a.x2][a.y2]-s[a.x1-1][a.y2]-s[a.x2][a.y1-1]+s[a.x1-1][a.y1-1];
}

int read() {
	int x=0,v=1; char ch=getchar();
	for (;ch<'0'||ch>'9';v=(ch=='-')?(-1):(v),ch=getchar());
	for (;ch<='9'&&ch>='0';x=x*10+ch-'0',ch=getchar());
	return x*v;
}

int main(void) {
	freopen("data.in","r",stdin);
	freopen("myp.out","w",stdout);
	int n,m,mina,minb,k;
	scanf("%d%d%d%d%d",&n,&m,&mina,&minb,&k);
	rep(i,1,n) rep(j,1,m) {
		s[i][j]=read();
		s[i][j]=s[i-1][j]+s[i][j-1]-s[i-1][j-1]+s[i][j];
	}
	rep(i,1,n-mina+1) {
		rep(j,1,m-minb+1) {
			data tmp=(data) {i,j,i+mina-1,j+minb-1};
			get_sum(tmp); heap.insert(tmp);
		}
	}
	long long tot=0;
	rep(i,mina,n) rep(j,minb,m) {
		tot+=1LL*(n-i+1)*(m-j+1);
	}
	if (tot<=k) {
		puts("-1");
		return 0;
	}
	for (;--k;) {
		top=*heap.begin(); heap.erase(top);
		if (top.x1>1) {
			tmp=(data) {top.x1-1,top.y1,top.x2,top.y2};
			get_sum(tmp); heap.insert(tmp);
		}
		if (top.x2<n) {
			tmp=(data) {top.x1,top.y1,top.x2+1,top.y2};
			get_sum(tmp); heap.insert(tmp);
		}
		if (top.y1>1) {
			tmp=(data) {top.x1,top.y1-1,top.x2,top.y2};
			get_sum(tmp); heap.insert(tmp);
		}
		if (top.y2<m) {
			tmp=(data) {top.x1,top.y1,top.x2,top.y2+1};
			get_sum(tmp); heap.insert(tmp);
		}
	}
	data top=*heap.begin(); get_sum(top);
	printf("%u\n", top.sum);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值