【王道機試筆記05】查找

查找

例2.9 找x

代碼2.12

#include<iostream>
using namespace std;
int main(){
	int n,i,x;
	int m[205];
	while(cin >> n){
		int ans = -1;
		for(i=0;i<n;i++){
			cin >> m[i];
		}
		cin >> x;
		for(i=0;i<n;i++){
			if(x == m[i]){
				ans = i;
				break;
			}
		}
		cout << ans << endl;
	}
	return 0;
}

例2.10 查找學生信息

代碼 2.13

二分搜索法,本來僅僅在每一次二分判斷的時候用一次strcmp就超時了,後來改成用tmp存儲就通過了。

#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
struct student{
	char num[20];
	string name;
	string sex;
	int age;
};
bool cmp(student x,student y){
	return strcmp(x.num,y.num) < 0;
}
int main(){
	int N,i;
	student stu[1005];
	while(cin >> N){
		for(i=0;i<N;i++){
			cin >> stu[i].num >> stu[i].name >> stu[i].sex >> stu[i].age;
		}
		sort(stu,stu + N,cmp);
		int M;
		cin >> M;
		while(M--){
			char x[20];
			cin >> x;
			int base,top,mid;
			base = 0;
			top = N - 1;
			int ans = -1;
			while(base <= top){
				mid = (base + top) / 2;
				int tmp = strcmp(stu[mid].num,x);
				if(tmp == 0){
					ans = mid;
					break;
				}
				else if(tmp < 0){
					base = mid + 1;
				}
				else
					top = mid - 1;
			}
			if(ans != -1)
				cout << stu[ans].num << ' ' << stu[ans].name << ' ' << stu[ans].sex << ' ' << stu[ans].age << endl;
			else
				cout << "No Answer!" << endl;
		}
	}
	return 0;
}

打印極值點下標

#include<iostream>
using namespace std;
int main(){
	int m[85];
	int k,i;
	while(cin >> k){
		for(i=0;i<k;i++)
			cin >> m[i];
		if(m[0] != m[1])
			cout << "0 ";
		for(i=1;i<k-1;i++)
			if(m[i] > m[i-1] && m[i] > m[i+1] || m[i] < m[i-1] && m[i] < m[i+1])
				cout << i << ' ';
		if(m[k-1] != m[k-2])
			cout << k-1;
		cout << endl;
	}
	return 0;
} 

查找

#include<iostream>
using namespace std;
int main(){
	int a[105],b[105];
	int N,M,i,j;
	while(cin >> N){
		for(i=0;i<N;i++)
			cin >> a[i];
		cin >> M;
		for(i=0;i<M;i++)
			cin >> b[i];
		for(i=0;i<M;i++){
			int flag = 0;
			for(j=0;j<N;j++)
				if(b[i] == a[j]){
					flag = 1;break;
				}
			if(flag == 1)
				cout << "YES" << endl;
			else
				cout << "NO" << endl;
		}
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章