Marlin_Phone @ 2024-12-02 23:39:23
// https://www.luogu.com.cn/problem/P2249
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
bool isblue(int num, int temp) {
if(num < temp) return true;
else return false;
}
int main(){
int n, m, temp;
scanf("%d%d", &n, &m);
vector<int> num(n + 10);
for (int i = 1; i <= n; i++) {
scanf("%d", &num[i]);
}
for (int i = 0; i < n; i++) {
scanf("%d", &temp);
int l = 0, r = n + 1;
while (l + 1 != r) {
int mid = (l + r) / 2;
if (isblue(num[mid], temp) == true) l = mid;
else r = mid;
}
if(num[r] == temp) printf("%d ", r);
else printf("-1 ");
}
return 0;
}
by Marlin_Phone @ 2024-12-02 23:41:36
孩子刚学完,做的第一道二分,问它也说没问题,求助 T_T
by pjh0625 @ 2024-12-03 06:23:10
@Marlin_Phone
#include<bits/stdc++.h>
using namespace std;
long long n,m,a[1000001],x,t;
int f(int t,int w,int x){
while(t<=w){
int mid=(t+w)/2;
if(a[mid]>=x){
w=mid-1;
}else{
t=mid+1;
}
}
if(t>n) return -1;
if(a[t]!=x) return -1;
return t;
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
for(int i=1;i<=m;i++){
scanf("%d",&x);
printf("%d ",f(1,n,x));
}
return 0;
}
我做的似乎有点复杂。。。
by Marlin_Phone @ 2024-12-05 21:58:52
@pjh0625 唉,我也知道这种写法,但是实在检查不出来自己到底错哪了 T_T 谢谢你
by pjh0625 @ 2024-12-05 22:15:44
@Marlin_Phone 我换种方法做了下,似乎是您的方法吧 。。。
#include <bits/stdc++.h>
using namespace std;
int main(){
int n, m, q;
scanf("%d%d", &n, &m);
int num[n];
int f[m];
for (int i = 0; i < n; i++) {
scanf("%d", &num[i]);
}
for (int i = 0; i < m; i++) {
scanf("%d", &q);
int l = 0, r = n;
while (l < r) {
int mid = (l + r) / 2;
if (num[mid] < q) {
l = mid + 1;
} else {
r = mid;
}
}
if (l < n && num[l] == q) {
f[i] = l + 1;
} else {
f[i] = -1;
}
}
for (int i = 0; i < m; i++) {
printf("%d ", f[i]);
}
return 0;
}
by pjh0625 @ 2024-12-05 22:17:50
我自学的,如有不足多包涵及指正