Kayleeeee @ 2024-02-29 23:30:05
#include<stdio.h>
const int N = 1e6 + 5;
int n, m;
int q[N];
int main()
{
scanf("%d %d", &n, &m);
for (int i = 1; i <= n; i++) scanf("%d", &q[i]);
while (m--)
{
int x;
scanf("%d", &x);
int l = 0, r = n - 1;
while (l < r)
{
int mid = l + r>>1;
if (q[mid] >= x) r = mid;
else l = mid + 1;
}
if (q[l] != x) printf("-1");
else printf("%d ", l);
}
return 0;
}
by syp11 @ 2024-03-01 00:20:22
两个问题
一个是输出-1后要加空格
另个是数据的标号是从1到n,所以二分的时候左右端点也应该是1到n
hack数据
3 5
1 2 3
0 1 2 3 4 5
改好的
#include<stdio.h>
const int N = 1e6 + 5;
int n, m;
int q[N];
int main()
{
scanf("%d %d", &n, &m);
for (int i = 1; i <= n; i++) scanf("%d", &q[i]);
while (m--)
{
int x;
scanf("%d", &x);
int l = 1, r = n ;
while (l < r)
{
int mid = l + r>>1;
if (q[mid] >= x) r = mid;
else l = mid + 1;
}
if (q[l] != x) printf("-1 ");
else printf("%d ", l);
}
return 0;
}
@Kayleeeee
by Kayleeeee @ 2024-03-01 13:29:12
@shiyupeng 好的,谢谢