Where is the Marble? 算法竞赛入门经典例题5-1

题目

链接

点此处跳转题目

输入

4 1
2
3
5
1
5
5 2
1
3
3
3
1
2
3
0 0

输出

CASE# 1:
5 found at 4
CASE# 2:
2 not found
3 found at 3

题解

题目简化

先给n个数,再给q个询问,输出该数排序后的位置

思路

sort排序的使用,会sort排个序就出来了

代码

蒟蒻的代码

#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
typedef long long ll;
const int maxco = 60;

int main() {
    
    
	int n,q,wt,sl=1;
	bool zd = 0;
	while (cin >> n>>q) {
    
    
		if (n==0&&q==0)
		{
    
    
			break;
		}
		int st[10050];
		for (int i = 0; i < n; i++)
		{
    
    
			cin >> st[i];
		}
		sort(st, st + n);//本题核心,sort排序,不会可以搜一搜别人的博客 
		cout << "CASE# " << sl << ":" << endl;//注意点(1)
		sl++;
		for (int i = 0; i < q; i++)
		{
    
    
			zd = 0;//我用了一个bool判断是否能够找到询问的数,能则赋值1
			cin >> wt;
			//下面利用循环去找询问的数,这一段可以优化------
			for (int find = 0; find < n&&st[find]<=wt; find++)//
			{
    
    
				if (st[find] == wt) {
    
    
					cout << wt << " found at " << find + 1 << endl;
					zd = 1;//找到了询问的数
					break;
				}
			
			}
			if (zd==0)
			{
    
    
				cout<<wt<<" not found" << endl;
			}
			//上一段可以优化------------
		}
	}

	return 0;
}

书上学到的优化

			int p = lower_bound(st, st + n, wt) - st;
			if (st[p]==wt)
			{
    
    
				cout << wt << " found at " << p+1 << endl;
			}
			else {
    
    
				cout << wt << " not found" << endl;
			}
			

这一段就是lower_bound的使用,其实可以直接手写二分查找,但我好懒orz,这题不难,就直接循环查找了

蒟蒻的收获

1、格式

cout << "CASE# " << sl << ":" << endl;

蒟蒻就是不好好读题,一个Q里面输出一次case,还傻傻不知道自己错在哪里!!!

2、lower_bound的使用

int p = lower_bound(st, st + n, wt) - st;

查找“大于或者等于x的第一个位置,可以优化循环查找,相当于二分查找
(首地址,尾地址,查找内容)-数组的地址

后记

这段时间参加了CCF认证,传智杯比赛,也刷了牛客练习赛,本蒟蒻本来有多写点博客的雄心壮志,结果现实很残酷,毕竟时间就像海绵里的水,用尽了力气也才挤出来一滴,直到今天才诞生了蒟蒻的第二篇博客
最近开始学紫书了,但期末考试临近,寒假也许能多一些博客吧

猜你喜欢

转载自blog.csdn.net/m0_52494226/article/details/111939008