Zhaozimo1207 @ 2024-03-30 23:55:41
我的代码:
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ll n,m,a[100005];
int find(int x){
int left = 1,right = n;
int middle = (left + right) / 2;
while(left < right){
if(a[middle] == x) return middle;
else if(x < a[middle]) middle = right;
else middle = left + 1;
}
return -1;
}
int main(){
cin >> n >> m;
for(int i = 1;i <= n;i ++){
cin >> a[i];
}
for(int i = 1;i <= m;i ++){
int x;
cin >> x;
cout << find(x) << " ";
}
return 0;
}
没有输出,求助
by Zhaozimo1207 @ 2024-03-30 23:57:21
可否帮我改一下代码,谢谢
by Forgotten_0114507666 @ 2024-03-31 00:34:03
@Zhaozimo1207
问题:
find
一点没对,全程left
和right
没改,只查找了随机一个 改完的:
#include<cstdio>
#include<cctype>
#define forr(i,a,b) for(int i=(a);i<=(b);i++)
#define roff(i,a,b) for(int i=(a);i>=(b);i--)
typedef long long ll;
inline ll max(ll a,ll b){return a>b?a:b;}
inline ll min(ll a,ll b){return a<b?a:b;}
inline void gmax(ll&a,ll b){if(a<b)a=b;}
inline void gmin(ll&a,ll b){if(a>b)a=b;}
inline ll abs(ll x){return x>0?x:-x;}
inline ll mod(ll x,ll m){return (x%m+m)%m;}
inline ll swap(ll&a,ll&b){a^=b^=a^=b;}
inline ll powm(ll x,ll p,ll m){
ll ret=1;
while(p){
if(p&1)ret=mod(ret*x,m);
x=mod(x*x,m);p>>=1;
}
return ret;
}
inline ll gcd(ll a,ll b){
if(b==0)return a;
return gcd(b,a%b);
}
ll qr(){
ll ans=0;int ch=getchar();bool sgn=false;
while(!isdigit(ch)){if(ch=='-')sgn=true;ch=getchar();}
while(isdigit(ch)){ans=(ans<<3)+(ans<<1)+(ch^'0');ch=getchar();}
return sgn?-ans:ans;
}
void qw(ll d,const char* append="",bool firstch=true){
if(firstch){
if(!d)putchar('0');
if(d<0)putchar('-'),d=-d;
}
if(d){
qw(d/10,"",false);
putchar(d%10 + '0');
}
if(firstch)fputs(append,stdout);
}
ll n,m,a[100005];
int find(int x){
int left = 1,right = n;
int middle;
while(left < right){
middle = (left + right ) / 2;
if(x <= a[middle]) right = middle;
else left = middle + 1;
}
if(a[left] == x)return left;
return -1;
}
int main(){
n=qr();m=qr();
for(int i = 1;i <= n;i ++){
a[i]=qr();
}
for(int i = 1;i <= m;i ++){
qw(find(qr()),"\n");
}
return 0;
}
by Zhaozimo1207 @ 2024-03-31 08:56:30
@Forgotten_0x1328FB6
感谢,编程小白,已AC