码迷,mamicode.com
首页 > 其他好文 > 详细

Search in a Binary Search Tree

时间:2015-04-13 18:33:44      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:

To search a key in a binary search tree, we start from the root and move all the way down, choosing branches according to the comparison results of the keys. The searching path corresponds to a sequence of keys. For example, following {1, 4, 2, 3} we can find 3 from a binary search tree with 1 as its root. But {2, 4, 1, 3} is not such a path since 1 is in the right subtree of the root 2, which breaks the rule for a binary search tree. Now given a sequence of keys, you are supposed to tell whether or not it indeed correspnds to a searching path in a binary search tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives two positive integers N and M (<=100) which are the total number of sequences, and the size of each sequence, respectively. Then N lines follow, each gives a sequence of keys. It is assumed that the keys are numbered from 1 to M.

Output Specification:

For each sequence, print in a line "YES" if the sequence does correspnd to a searching path in a binary search tree, or "NO" if not.

Sample Input:

3 4
1 4 2 3
2 4 1 3
3 2 4 1

Sample Output:

YES
NO
NO

解题思路:如果第i+1个数比i个数大(小),i+1后面的数都比i大(小)
解题感悟:可以用标志位连续跳出两个for循环

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 int main(){
 5     int n, m;
 6     cin >> n >> m;
 7     for (int i = 0; i < n;i++)
 8     {
 9         int flag = 0;
10         vector<int> v;
11         for (int j = 0; j < m;j++)
12         {
13             int elem;
14             cin >> elem;
15             v.push_back(elem);
16         }
17         for (int j = 0; j < m - 2;j++)
18         {
19             if (v[j]>v[j + 1])
20             {
21                 for (int k = j + 2; k < m;k++)
22                 {
23                     if (v[k]>=v[j])
24                     {
25                         flag = 1;
26                         break;
27                     }
28                 }
29             }
30             else
31             {
32                 for (int k = j + 2; k < m; k++)
33                 {
34                     if (v[k] <= v[j])
35                     {
36                         flag = 1;
37                         break;
38                     }
39                 }
40             }
41             if (flag == 1)
42                 break;
43         }
44         if (flag == 1)
45             cout << "NO"<<endl;
46         else
47             cout << "YES"<<endl;
48     }
49     return 0;
50 }

 

 

Search in a Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/lkyblog/p/4422685.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!