PAT 数据结构 04-树7. Search in a Binary Search Tree (25)

该博客讨论了如何在二叉搜索树中搜索键值,通过比较键来确定搜索路径。每个有效的搜索路径对应一系列键。例如,序列{1, 4, 2, 3}可以表示从根节点1开始找到3的路径。但是,序列{2, 4, 1, 3}不符合二叉搜索树规则。输入包含多个序列,需要判断每个序列是否对应二叉搜索树的有效路径。如果符合,输出'YES',否则输出'NO'。" 113509991,10536205,Python BRISQUE:无参考图像质量评估,"['图像处理', 'Python', 'OpenCV', '图像质量', '无参考评估']
摘要由CSDN通过智能技术生成

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
 
    比较简单,若a[i]<a[i+1],则判断后面的数是否都大于a[i];若a[i]>a[i+1],则判断后面的数是否都小于a[i]。
#include <iostream>
#include <vector>
using namespace std;
int main(){
	int N,M;
	cin>>N>>M;
	vector<int> a(M);
    bool flag =true;
	while(N--){
		for(int i=0;i<M;i++)
			cin>>a[i];
		flag=true;
		for(int i=0;i<M-1;i++){
			if(a[i]<a[i+1])
				for(int j=i+1;j<M;j++){
					if(a[i]>a[j]){
						cout<<"NO"<<endl;
						flag=false;
						break;
					}
				}
			else
				for(int j=i+1;j<M;j++){
					if(a[i]<a[j]){
						cout<<"NO"<<endl;
						flag=false;
						break;
					}
				}
			if(!flag)
				break;
		}
		if(flag)
			cout<<"YES"<<endl;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值