题目描述
You received a card at a banquet. On the card, a matrix of N rows and M columns and two integers K and S are written. All the elements in the matrix are integers, and an integer at the i-th row from the top and the j-th column from the left is denoted by Ai,j.
You can select up to K elements from the matrix and invert the sign of the elements. If you can make a matrix such that there is no vertical or horizontal contiguous subsequence whose sum is greater than S, you can exchange your card for a prize.
Your task is to determine if you can exchange a given card for a prize.
输入
The input consists of a single test case of the following form.
N M K S
A1,1 A1,2 … A1,M
:
AN,1 AN,2 … AN,M
The first line consists of four integers N,M,K and S (1≤N,M≤10,1≤K≤5,1≤S≤106). The following N lines represent the matrix in your card. The (i+1)-th line consists of M integers Ai,1,Ai,2,…,Ai,M(−105≤Ai,j≤105).
输出
If you can exchange your card for a prize, print ‘Yes’. Otherwise, print ‘No’.
样例输入
3 3 2 10
5 3 7
2 6 1
3 4 1
样例输出
Yes
提示
The sum of a horizontal contiguous subsequence from A1,1 to A1,3 is 15. The sum of a vertical contiguous subsequence from A1,2 to A3,2 is 13. If you flip the sign of A1,2, there is no vertical or horizontal contiguous subsequence whose sum is greater than S.
思路
整理矩阵,标出超出标准的行和列,进行dfs剪枝
代码实现
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=100;
int n,m,k,s;
int a[N][N];
bool row[N],col[N];
bool pre_h(int t)
{
int tmp=0;
for(int i=1;i<=m;i++)
{
tmp+=a[t][i];
if(tmp>s) return true;
if(tmp<0) tmp=0;
}
return false;
}
bool pre_l(int t)
{
int tmp=0;
for(int i=1;i<=n;i++)
{
tmp+=a[i][t];
if(tmp>s) return true;
if(tmp<0) tmp=0;
}
return false;
}
bool dfs(int x,int y,int cnt)
{
if(y==m+1) return dfs(x+1,1,cnt);
if(x<=n && (a[x][y]<=0 || (!row[x] && !col[y]))) return dfs(x,y+1,cnt);
int cnt1=0,cnt2=0;
for(int i=1;i<=n;i++)
{
if(i<x && row[i]) return false;
cnt1+=row[i];
}
for(int i=1;i<=m;i++) cnt2+=col[i];
if(cnt1>cnt || cnt2>cnt) return false;
if(cnt1==0 && cnt2==0) return true;
if(x==n+1 || cnt==0) return false;
if(dfs(x,y+1,cnt)) return true;
if((row[x]||col[y]) && a[x][y]>0)
{
bool r=row[x],c=col[y];
a[x][y]*=-1;
row[x]=pre_h(x);
col[y]=pre_l(y);
if(dfs(x,y+1,cnt-1)) return true;
a[x][y]*=-1;
row[x]=r;
col[y]=c;
}
return false;
}
int main()
{
scanf("%d%d%d%d",&n,&m,&k,&s);
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++) scanf("%d",&a[i][j]);
for(int i=1;i<=n;i++) row[i]=pre_h(i);
for(int i=1;i<=m;i++) col[i]=pre_l(i);
if(dfs(1,1,k)) puts("Yes");
else puts("No");
return 0;
}