Give you N numbers a[1]...a[n]
and M numbers b[1]...b[m]
For each b[k], if we can find i,j a[i] + a[j] = b[k] or a[i] = b[k] , we say k is a good number.
And you should only output the number of good numbers.
0 < n, m, a[i], b[j] <= 200000
sample input
3 6
1
3
5
2
4
5
7
8
9
sample output
4
b[1]...b[m] 2,4,5,7,8,9
2 = 1+1
4 = 1+3
5 = 5
8 = 3+5
详细分析,首先如果b[k]在a数组中出现,那么这个k是符合条件的
对于每个b[k]枚举i,j看能否满足a[i]+a[j]=a[k] 的做法应该会超时。但是O(n*m)的做法可能可以过。
有一种利用bitset的非标准做法。利用bitset记录哪些数在a中出现过了。那么把这个bitset左移1位,我们就可以得到有哪些x(x=a[i]+1)出现过了。左移两位,就知道哪些x(x = a[i]+2)出现过。如果此处左移a[1]那么,得到的就是a[1]+a[1] ,... ,a[1]+a[n]这些数字的bitset。枚举a[1]到a[n]来左移,把结果取或,就能得到a[i]+a[j]的集合,再或上a[1]..a[n]的bitset,把这个结果和b[1]..b[m]的bitset取&, 剩下的这个bitset有多少个1,答案就是几。
另外有一个技巧,我们先把a数组排序(题目并没有保证a数组有序)对于一个集合,先左移a[1]次,之后都把之前的答案左移a[i]-a[i-1]次。
bitset做法:
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <bitset>
using namespace std;
const int maxn = 50001;
bitset<maxn> goal, now, tmp;
int a[maxn], n, m;
void work() {
scanf("%d", &m);
goal.reset();
now.reset();
for (int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
now.set(a[i]);
}
// scanf("%d", &m);
for (int i = 1; i <= m; ++i) {
int k;
scanf("%d", &k);
goal.set(k);
}
sort(a + 1, a + n + 1);
tmp = now;
for (int i = 1; i <= n; ++i) {
tmp = tmp << (a[i] - a[i - 1]);
now = now | tmp;
}
goal = goal & now;
printf("%d\n", goal.count());
}
int main() {
while (scanf("%d", &n) != EOF) work();
}
简单做法:
#include<iostream>
using namespace std;
int main() {
int n, m, a[200000], b[200000], s= 0, s1= 0;
cin>> n>> m;
for (int i= 0; i< n; i++)
cin>> a[i];
for (int i= 0; i< m; i++)
cin>> b[i];
for (int i= 0; i< m; i++) {
for (int j= 0; j< n; j++) {
int f= 0;
if (b[i]== a[j]) {
s++;
break;
}
for (int k= j; k< n; k++) {
if (b[i]== a[j]+ a[k]) {
s++;
f= 1;
break;
}
}
if (f== 1) break;
}
}
cout<< s<< endl;
}
显然用bitset比o(m*n*n)简单方法的时间复杂度要大大降低。