题目1384:二维数组中的查找

题目描述:

在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

 

输入:

输入可能包含多个测试样例,对于每个测试案例,

输入的第一行为两个整数m和n(1<=m,n<=1000):代表将要输入的矩阵的行数和列数。

输入的第二行包括一个整数t(1<=t<=1000000):代表要查找的数字。

接下来的m行,每行有n个数,代表题目所给出的m行n列的矩阵(矩阵如题目描述所示,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。

 

输出:

对应每个测试案例,

输出”Yes”代表在二维数组中找到了数字t。

输出”No”代表在二维数组中没有找到数字t。

 

样例输入:
3 3
5
1 2 3
4 5 6
7 8 9
3 3
1
2 3 4
5 6 7
8 9 10
3 3
12
2 3 4
5 6 7
8 9 10
样例输出:
Yes
No
No

 1 #include <iostream> //1384
 2 #include <algorithm>
 3 #include <set> 
 4 #include <map>
 5 #include <list>
 6 #include <deque>
 7 #include <queue>
 8 #include <stack>
 9 #include <vector>
10 #include <string>
11 #include <fstream>
12 #include <cmath>
13 #include <ctime>
14 #include <cstdio>
15 #include <cctype>
16 #include <cstring>
17 #include <sstream>
18 #include <cstdlib>
19 #include <cassert>
20  
21 using namespace std;
22  
23 int martix[1001*1001];
24  
25 int M;
26 int N;
27  
28 bool binarysearch(int t ,int begin, int end )
29 {
30     int left = begin;
31     int right = end;        
32     while( left<= right )
33     {
34         int mid = (left+right)/2;
35         if( t == martix[mid] )
36         {
37             return true;
38         }
39         else if( t > martix[mid] )
40         {
41             left = mid+1;
42         }
43         else
44         {
45             right = mid-1;
46         }
47     }
48     return false;
49 }
50  
51 int main()
52 {
53     int m;
54     int n;
55     int t;
56     int i;
57     int j;
58  
59     while( scanf("%d%d",&m,&n) != EOF)
60     {
61         M = m;
62         N = n;
63         memset(martix,0,sizeof(martix));
64         scanf("%d",&t);
65         for(i = 0 ;i < m; i++)
66             for(j = 0; j < n; j++)
67                  scanf("%d",&martix[n*i+j]);
68          
69         if(!binarysearch(t,0,m*n-1))
70             printf("No\n");
71         else
72             printf("Yes\n");
73     }
74          
75     return 0;
76 }

 


posted @ 2013-12-09 20:15  chchche  阅读(226)  评论(0编辑  收藏  举报