题目链接:http://ac.jobdu.com/problem.php?pid=1384
剑指Offer的解释:http://www.cnblogs.com/zhuyf87/archive/2013/03/01/2938013.html
开始的时候思路卡在如果降低时间复杂度上,我想的选点是选左上角和右下角,但是显然复杂度太高......也考虑过蛇形把矩阵剥皮,还考虑过随机选点,然后每次删除一大块留一个一个小矩阵(这个会挺复杂)
现在想想其实哪怕把各种可能的对矩阵的遍历方式都试一遍差不多也能有正确思路。
正确思路就是选左下或者右上的点,这样每次能删除一列
我用的递归写的:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int SIZE = 1001;
int n,m;
int t;
int mat[SIZE][SIZE];
bool getTar(int rs,int rt, int cs, int ct){
int nct = ct;
for(int i=ct;i>=cs;i--){
if(mat[rs][i]>t)nct--;
else{
if(mat[rs][i] == t)return 1;
else{
break;
}
}
}
//nct--;
int nrs = rs;
for(int i=rs;i<=rt;i++){
if(mat[i][nct]<t)nrs++;
if(mat[i][nct] == t)return 1;
if(mat[i][nct]>t)break;
}
//nrs++;
if(nrs >rt || nct < cs)return 0;
return getTar( nrs, rt, cs, nct);
}
int main(){
//freopen("in.txt","r",stdin);
while(~scanf("%d%d%d",&m,&n,&t)){
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
scanf("%d",&mat[i][j]);
}
}
if(getTar(0,m-1,0,n-1)){
printf("Yes");
}else{
printf("No");
}
printf("\n");
}
return 0;
}
/**************************************************************
Problem: 1384
User: Zafedom
Language: C++
Result: Accepted
Time:690 ms
Memory:5432 kb
****************************************************************/
书上O(n)循环搞之
#include <cstdio>
#include <cstring>
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int SIZE = 1001;
int n,m;
int t;
int mat[SIZE][SIZE];
bool getTar(int rs, int rt, int cs, int ct){
bool result = false;
if(rt<rs || ct < cs || mat == NULL)return false;
int nrs=rs, nct=ct;
while(nrs <=rt && nct >=cs){
if(mat[nrs][nct] == t)return true;
else{
if(mat[nrs][nct] > t){
nct--;
}else{
nrs++;
}
}
}
return result;
}
int main(){
//freopen("in.txt","r",stdin);
while(~scanf("%d%d%d",&m,&n,&t)){
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
scanf("%d",&mat[i][j]);
}
}
if(getTar(0,m-1,0,n-1)){
printf("Yes");
}else{
printf("No");
}
printf("\n");
}
return 0;
}