翻译:
您将得到一个包含𝑛行和𝑚列的网格。我们在𝑖-th表示广场(1≤𝑖≤𝑛)行和𝑗-th(1≤𝑗≤𝑚)列(𝑖𝑗)和数量在𝑎𝑖𝑗。所有数字都等于1或−1。
你可以从方块(1,1)开始,每次向下移动一个方块或向右移动一个方块。最后,你想在广场(𝑛,𝑚)结束。
是否可能以这样一种方式移动,使写入所有访问单元格(包括𝑎11和𝑎𝑛𝑚)的值的总和为0?
输入
每个测试包含多个测试用例。第一行包含测试用例的数量𝑡(1≤𝑡≤104)。测试用例的描述如下。
每个测试用例的第一行包含两个整数𝑛和𝑚(1≤𝑛,𝑚≤1000)——网格的大小。
下面的每一行𝑛都包含𝑚整数。𝑗-th整数𝑖-th线是𝑎𝑖𝑗(𝑎𝑖𝑗= 1或−1)-细胞中的元素(𝑖𝑗)。
保证所有测试用例𝑛⋅𝑚的总和不超过106。
输出
对于每个测试用例,如果存在从左上到右下的路径加起来为0,则打印“YES”,否则打印“NO”。您可以在任何情况下输出每个字母。
例子
inputCopy
5
1
1
1 2
1
1 - 4
1 -1 1 -1
3 4
1 -1 -1 -1
-1 1 1 1
1 1 1 -1
3 4
1 -1 1 1
-1 1 -1 1
1 -1 1 1
outputCopy
没有
是的
是的
是的
没有
请注意
第四个测试用例的一个可能的路径在语句中的图片中给出。
思路:
路径到达,并且路途和相加等于0。从初位置到末位置,如果n+m是偶数那么路过的路径一定是奇数。所以相加不可能等于0。之后我们发现,如果到末位置的路径最大值大于等0和路径的最小值小于等于0,那么到最后末位置,一定可以走出一条等于0的路径(可以手画实践一下)。所以我们用动态规划来求解。
代码:
#include <iostream>
#include <algorithm>
#include <string.h>
#include <string>
#include <math.h>
#include <stdio.h>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<tuple>
#include<numeric>
#include<stack>
using namespace::std;
typedef long long ll;
int n,t;
inline __int128 read(){
__int128 x = 0, f = 1;
char ch = getchar();
while(ch < '0' || ch > '9'){
if(ch == '-')
f = -1;
ch = getchar();
}
while(ch >= '0' && ch <= '9'){
x = x * 10 + ch - '0';
ch = getchar();
}
return x * f;
}
inline void print(__int128 x){
if(x < 0){
putchar('-');
x = -x;
}
if(x > 9)
print(x / 10);
putchar(x % 10 + '0');
}
int na[1005][1005];
ll dp[1005][1005];
ll dp1[1005][1005];
int m;
void solv(){
cin>>n>>m;
for (int i =1; i<=n; i++) {
for (int j =1; j<=m; j++) {
cin>>na[i][j];
}
}
if((n+m)%2==0){
printf("NO\n");return;
}
for (int i =1; i<=n; i++) {
for (int j =1; j<=m; j++) {
dp[i][j]=max(dp[i-1][j], dp[i][j-1])+na[i][j];
dp1[i][j]=min(dp1[i-1][j], dp1[i][j-1])+na[i][j];
}
}
// for (int i =1; i<=m; i++) {
// printf("%lld ",dp1[1][i]);
// }printf("\n");
// printf("%lld %lld\n",dp[n][m],dp1[n][m]);
if (dp[n][m]>=0 && dp1[n][m]<=0) {
printf("YES\n");
}
else
printf("NO\n");
}
int main(){
ios::sync_with_stdio(false);
cin.tie(); cout.tie();
cin>>t;
while (t--) {
dp[1][0]=dp[0][1]=0;
dp1[1][0]=dp1[0][1]=0;
for (int i = 2; i<=1005; i++) {
dp[i][0]=-1e17;
dp1[i][0]=1e17;
}
for (int i =2; i<=1005; i++) {
dp[0][i]=-1e17;
dp1[0][i]=1e17;
}
solv();
}
return 0;
}