Youuu888 @ 2024-01-13 21:08:07
如题,参考一个C++可以过的全部TLE
这个是80分的```c
int M[1000050];
int main() { int n, m; //m是查询次数 scanf("%d %d", &n, &m);
for (int i = 1; i <= n; i++) {
scanf("%d", &M[i]);
}
for (int i = 0; i < m; i++) {
int num;
scanf("%d", &num);
int relust = -1;
int right = n;
int lift = 1;
while (lift <= right) {
int mid = (lift + right ) / 2;
if (num == M[mid]) {
relust = mid;
for (int i = mid - 1; i >= lift; i--) {
if (num == M[i]) {
relust = i;
}
}
break;
} else if (num < M[mid]) {
right = mid - 1;
} else if (num > M[mid]) {
lift = mid + 1;
}
}
printf("%d ", relust);
}
return 0;
}
这个是C++可以过的
```cpp
#include<bits/stdc++.h>
using namespace std;
const int N = 1000010;
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 - l) / 2;
if (q[mid] >= x) r = mid;
else l = mid + 1;
}
if (q[l] == x) printf("%d ", l);
else printf("-1 ");
}
return 0;
}
参考上面用c的全部tle
#include <stdio.h>
#include <string.h>
int M[1000050];
int main(void) {
int n, m; //m是查询次数
scanf("%d %d", &n, &m);
for (int i = 1; i <= n; i++) {
scanf("%d", &M[i]);
}
while (m--) {
int num;
scanf("%d", &num);
int right = n;
int lift = 1;
while (lift < right) {
int mid = lift + (1 + right ) / 2;
if (M[mid] >= num) {
right = mid;
} else {
lift = mid + 1;
}
}
if (M[lift] == num) {
printf("%d", num);
} else {
printf("-1");
}
}
}
by xiaoshumiao @ 2024-01-13 21:10:38
@Youuu888
int mid = lift + (1 + right ) / 2;
写错了吧。
by xiaoshumiao @ 2024-01-13 21:11:03
改成:
int mid = lift + (right -lift) / 2;
by xiaoshumiao @ 2024-01-13 21:12:27
还有,你忘输出空格了。
by xiaoshumiao @ 2024-01-13 21:15:27
而且输出的是 lift 不是 num。
by xiaoshumiao @ 2024-01-13 21:16:44
改完这些就过了。 @Youuu888
by Youuu888 @ 2024-01-13 21:25:48
@xiaoshumiao 好的谢谢,还是太马虎了