二分学习
Posted starry
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二分学习相关的知识,希望对你有一定的参考价值。
题目描述
给定2个数组a、b以及一个整数x
判断是否存在a[i]+b[j]=x
输入
第一行:两个整数n、m (1<n、m<10000)
第二行:n个整数,为数组a
第三行:m个整数,为数组b
第四行:一个整数k (1<k<20),表示k次查询
接下来的k行:每行一个整数x
输出
若数组a中存在一个a[i],数组b中存在一个b[j],使得a[i]+b[j]=x,则输出Yes
如不存在,则输出No
样例输入
2 3
1 2
3 4 5
4
1
4
5
8
样例输出
No
Yes
Yes
No
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 using namespace std; 5 const int maxn = 1e5+7; 6 int a[maxn], b[maxn]; 7 int query(int *arr, int l, int r, int key){ 8 while(l <= r){ 9 int mid = (l + r) >> 1; 10 if(arr[mid] == key) return mid; 11 if(arr[mid] < key) l = mid + 1; 12 else r = mid - 1; 13 } 14 return -1; 15 } 16 int main() 17 { 18 int n, m, k; 19 scanf("%d%d",&n,&m); 20 for(int i = 0; i < n; i++)scanf("%d",&a[i]); 21 for(int i = 0; i < m; i++)scanf("%d",&b[i]); 22 cin >> k; 23 sort(a, a + n);sort(b, b + m); 24 int q; 25 while(k--){ 26 cin >> q; 27 int flag = 1; 28 for(int i = 0; i < n; i++){ 29 int y = q - a[i]; 30 //cout << y << endl; 31 if(y > 0){ 32 int pos = query(b, 0, m, y); 33 if(pos != -1){ 34 cout << "Yes" << endl; 35 flag = 0; 36 break; 37 } 38 } 39 40 } 41 if(flag == 1){ 42 cout << "No" << endl; 43 } 44 } 45 return 0; 46 }
670 D2
The term of this problem is the same as the previous one, the only exception — increased restrictions.
The first line contains two positive integers n and k (1?≤?n?≤?100?000,?1?≤?k?≤?10^9) — the number of ingredients and the number of grams of the magic powder.
The second line contains the sequence a1,?a2,?...,?an (1?≤?ai?≤?10^9), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie.
The third line contains the sequence b1,?b2,?...,?bn (1?≤?bi?≤?10^9), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has.
Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder.
1 1000000000
1
1000000000
2000000000
10 1
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000
1 1 1 1 1 1 1 1 1 1
0
3 1
2 1 4
11 3 16
4
4 3
4 3 5 6
11 12 14 20
3
1 #include <iostream> 2 #include <cstdio> 3 #define ll long long 4 using namespace std; 5 const int maxn = 1e5+7; 6 ll a[maxn], b[maxn]; 7 8 int main() 9 { 10 ll n, k; 11 while(~scanf("%lld%lld",&n,&k)){ 12 for(int i = 0; i < n; i++)scanf("%lld",&a[i]); 13 for(int i = 0; i < n; i++)scanf("%lld",&b[i]); 14 ll mid, sum, flag, l = 0, r = 2e9+10; 15 while(l <= r){ 16 mid = (l + r) >> 1; 17 sum = 0;flag = 1; 18 for(int i = 0; i < n; i++){ 19 if(a[i]*mid > b[i]){ 20 sum += a[i]*mid - b[i]; 21 } 22 if(sum > k){ 23 flag = 0; 24 } 25 } 26 //cout << l << ‘ ‘ << r << endl; 27 if(flag) l = mid + 1; 28 else r = mid - 1; 29 } 30 printf("%lld\n",l - 1); 31 } 32 33 return 0; 34 }
以上是关于二分学习的主要内容,如果未能解决你的问题,请参考以下文章