P2249 【深基13.例1】查找

https://www.luogu.com.cn/problem/P2249

輸入 n(n\le10^6)n(n≤106) 個不超過 10^9109 的單調不減的(就是後面的數字不小於前面的數字)非負整數 a_1,a_2,\dots,a_{n}a1​,a2​,…,an​,然後進行 m(m\le10^5)m(m≤105) 次詢問。對於每次詢問,給出一個整數 q(q\le10^9)q(q≤109),要求輸出這個數字在序列中的編號,如果沒有找到的話輸出 -1 。

輸入格式

第一行 2 個整數 n 和 m,表示數字個數和詢問次數。

第二行 n 個整數,表示這些待查詢的數字。

第三行 m 個整數,表示詢問這些數字的編號,從 1 開始編號。

輸出格式

m 個整數表示答案。

輸入輸出樣例

輸入 #1複製

11 3
1 3 3 3 5 7 9 11 13 15 15
1 3 6

輸出 #1複製

1 2 -1 

這題意義在於讓我發現了我之前總結的板子邊界又有問題。重新更正了。https://blog.csdn.net/zstuyyyyccccbbbb/article/details/107106402

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1e6+10;
typedef long long LL;
LL a[maxn];
LL bsearch(LL l,LL r,LL q)
{
	while(l<r)
	{
		LL mid=(l+r)>>1;
		if(a[mid]>=q) r=mid;
		else l=mid+1;
	}
	return l;
} 
int main(void)
{
	LL n,m;cin>>n>>m;
	for(LL i=1;i<=n;i++) cin>>a[i];
	while(m--)
	{
		LL q;cin>>q;
		LL t=bsearch(1,n+1,q);
	//	cout<<"t=="<<t<<endl;
	//	cout<<"a[t]=="<<a[t]<<endl;
		if(t==n+1||a[t]!=q) cout<<"-1"<<' ';
		else cout<<t<<' ';
	}
return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章