HDU 2141 - Can you find it? ( 二分查找 )

思路

500*500*500*1000 复杂度太高无法暴力求解

AC代码(手写二分查找)

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#define mst(a) memset(a, 0, sizeof(a))
using namespace std;
const int maxn = 500+5;
typedef unsigned long long ll;
ll a[maxn], b[maxn], c[maxn], ab[maxn*maxn];

void init(){
mst(a);mst(b);mst(c);mst(ab);
}

int binsearch(ll arr[], int len, int key)
{
int left = 0;
int right = len - 1;
int mid;
while(left <= right){
mid = (left + right)/2;
if (key <= arr[mid])  right = mid - 1;
else   left = mid + 1;
}
if(left < len && arr[left] == key)
return left;
return -1;
}

int main()
{
int l, m, n, k, t;
int kase = 0;
while( ~scanf("%d%d%d",&l, &m, &n) ){
init();
for( int i = 0; i < l; i++ )   scanf("%llu",&a[i]);
for( int i = 0; i < m; i++ )   scanf("%llu",&b[i]);
for( int i = 0; i < n; i++ )   scanf("%llu",&c[i]);
printf("Case %d:\n",++kase);
sort(c, c+n);
k = -1;
for( int i = 0; i < l; i++ )
for( int j = 0; j < m; j++ )
ab[++k] = a[i] + b[j];
sort(ab, ab+k);
int len = k;
scanf("%d",&t);
while(t--){
scanf("%d",&k);
bool flag = false;
for( int i = 0; i < n; i++ ){
int xx = k - c[i];
if( binsearch( ab, len, xx ) != -1 ){
printf("YES\n");
flag = true;
break;
}
}
if(!flag) printf("NO\n");
}
}
return 0;
}


AC代码(STL)

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>

#define mst(a) memset(a, 0, sizeof(a))
using namespace std;
const int maxn = 500+5;
typedef long long ll;
ll a[maxn], b[maxn], c[maxn], ab[maxn*maxn];

void init(){
mst(a);mst(b);mst(c);mst(ab);
}

int main()
{
int l, m, n, k, t;
int kase = 0;
while( ~scanf("%d%d%d",&l, &m, &n) ){
init();
for( int i = 1; i <= l; i++ )   scanf("%lld",&a[i]);
for( int i = 1; i <= m; i++ )   scanf("%lld",&b[i]);
for( int i = 1; i <= n; i++ )   scanf("%lld",&c[i]);
printf("Case %d:\n",++kase);
sort(c+1, c+n+1);
k = 0;
for( int i = 1; i <= l; i++ )
for( int j = 1; j <= m; j++ )
ab[++k] = a[i] + b[j];
sort(ab+1, ab+k+1);
int len = k;
scanf("%d",&t);
while(t--){
scanf("%d",&k);
bool flag = false;
for( int i = 1; i <= n; i++ ){
int xx = k - c[i];
if( binary_search( ab+1, ab+len+1, xx ) != 0 ){
printf("YES\n");
flag = true;
break;
}
}
if(!flag) printf("NO\n");
}
}
return 0;
}


• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120