10 条题解
-
7
#include <iostream> using namespace std; int a[100005]; int main() { int n, q, x; cin >> n; for (int i = 1 ; i <= n ; i++) cin >> a[i]; cin >> q; for (int i = 1 ; i <= q ; i++) { cin >> x; int l = 1, r = n, mid; while (l <= r) { mid = (l + r) / 2; if (a[mid] < x) l = mid + 1; else if (a[mid] > x) r = mid - 1; else break; } int first = mid; while (a[first] == x) first--; if (first == mid) first = -1; else first++; cout << first << " "; } return 0; } //代码已AC
-
2
服了呀!8个AC,2个TLE!
#include <iostream> using namespace std; int main() { int n,q,x; cin>>n; int a[n+1]; for (int i=1;i<=n;i++)cin>>a[i]; cin>>q; for (int i=1;i<=q;i++) { cin>>x; int ans=0; for (int j=1;j<=n;j++) { if (a[j]==x) { ans++; cout<<j<<" "; break; } } if (ans==0)cout<<"-1 "; } return 0; }
-
2
-
2
#include <bits/stdc++.h> using namespace std; int a[10000005]; int main() { int n, m, x, l, r, ans; cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; cin >> m; for (int i = 1; i <= m; i++){ cin >> x; l = 1; r = n; ans = -1; while (l <= r){ int mid = (l + r) / 2; if (a[mid] >= x){ if (a[mid] == x) ans = mid; r = mid - 1; }else{ l = mid + 1; } } cout << ans << " "; } }
-
0
#include<bits/stdc++.h> using namespace std; int a[1000001],n,x; int Find(int low,int high) { if(a[low]>x||a[high]<x||low>high) return -1; int mid=(low+high)/2; if(a[mid]==x) { if(low==high) //虽然找到 a[mid]=x,但是它不一定是首次出现的,还要继续找 return mid; else return Find(low,mid); } else if(a[mid]<x) return Find(mid+1,high); else return Find(low,mid-1); } int main() { int i,q; scanf("%d",&n); for(i=1;i<=n;i++) scanf("%d",&a[i]); scanf("%d",&q); while(q--) { scanf("%d",&x); printf("%d ",Find(1,n)); } return 0; }
-
0
#include <cstdio> using namespace std; int main(){ int n,x,q,l,r,mid,pos,a[100001]; scanf("%d",&n); for(int i=1;i<=n;i++)scanf("%d",&a[i]); scanf("%d",&q); for(int i=1;i<=q;i++){ l=1,r=n,pos=-1; scanf("%d",&x); while(l<=r){ mid=(l+r)/2; if(a[mid]==x)pos=mid; a[mid]>=x?r=mid-1:l=mid+1; } printf("%d%c",pos,' '); } printf("\n"); return 0; }
-
0
#include <bits/stdc++.h> using namespace std; int n,q,x; int a[100005]; int main(){ cin>>n; for (int i=1;i<=n;i++){ cin>>a[i]; } sort(a+1,a+n+1); cin>>q; while (q--){ cin>>x; int l=1,r=n; while (l<=r){ int mid=(l+r)>>1; if (a[mid]>=x){//大于等于可以保证找到第一次出现的位置 r=mid-1; }else{ l=mid+1; } } cout<<(a[l]==x?l:-1)<<" ";//特判找不到的情况 } return 0; }
- 1
信息
- ID
- 890
- 时间
- 1000ms
- 内存
- 128MiB
- 难度
- 6
- 标签
- 递交数
- 1168
- 已通过
- 390
- 上传者