总结
- 思路
这个神奇的题WA了8次,折在了各种奇葩的问题上,其实就是标准的二分查找模版题
大数暴力会爆炸,枚举三个数组,时间复杂度O(N^3)。
解决的方法是进行预处理操作。将本来同时进行,多层循环中的某些层拉出来,分部操作。首先将前两个数组进行枚举得到和数组,时间复杂度O(n^2),然后枚举第三个数组,在和数组中找值,查找为了节省时间,选用二分。
- 错误
首先是vector的使用,刚开始接触,就觉得很好用,除了可以当成数组一样用之外还有很多附加的函数,但是若使用push_back操作来代替数组中的赋值要注意,对于多组数据测试来说,每组数据要记得清空vector。
WA的错误还有一次是超内存,开始以为是因为long long 500*500的原因,其实这个是不会超的,超的原因是初始化为0的错写在了多组数据循环的外面,这样不断测试之后后面数组就越开越大。
Description
Give you three sequences of numbers A, B, C, then we give you a number X. Now you need to calculate if you can find the three numbers Ai, Bj, Ck, which satisfy the formula Ai+Bj+Ck = X.
Input
There are many cases. Every data case is described as followed: In the first line there are three integers L, N, M, in the second line there are L integers represent the sequence A, in the third line there are N integers represent the sequences B, in the forth line there are M integers represent the sequence C. In the fifth line there is an integer S represents there are S integers X to be calculated. 1<=L, N, M<=500, 1<=S<=1000. all the integers are 32-integers.
Output
For each case, firstly you have to print the case number as the form "Case d:", then for the S queries, you calculate if the formula can be satisfied or not. If satisfied, you print "YES", otherwise print "NO".
Sample Input
3 3 3
1 2 3
1 2 3
1 2 3
3
1
4
10
Sample Output
Case 1:
NO
YES
NO
代码
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
int a[505],b[505],c[505];
vector<int> d;
int main(void)
{
int l,n,m,s;
int T = 0;
while(scanf("%d%d%d",&l,&n,&m)!=EOF)
{
d.clear();//用vector记得清空
printf("Case %d:\n",++T);
for(int i = 0;i<l;i++) scanf("%d",&a[i]);
for(int i = 0;i<n;i++) scanf("%d",&b[i]);
for(int i = 0;i<m;i++) scanf("%d",&c[i]);
for(int i = 0;i<l;i++)
{
for(int j = 0;j<n;j++)
{
d.push_back(a[i]+b[j]);
}
}
sort(d.begin(),d.end());
scanf("%d",&s);
int x;
while(s--)
{
int flag = 0;
scanf("%d",&x);
for(int i = 0;i<m;i++)
{
int left = 0,right = d.size()-1,mid;
while(left<=right)
{
mid = (left+right)/2;
if(d[mid]==x-c[i])
{
flag = 1;
break;
}
else if(d[mid]<x-c[i]) left = mid+1;
else right = mid-1;
}
}
if(flag) printf("YES\n");
else printf("NO\n");
}
}
return 0;
}