HDU 2143 Can you find it?(基础二分)
Posted caiyishuai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU 2143 Can you find it?(基础二分)相关的知识,希望对你有一定的参考价值。
Can you find it?
Time Limit: 10000/3000 MS (Java/Others) Memory Limit: 32768/10000 K (Java/Others)
Total Submission(s): 42520 Accepted Submission(s): 10315
Problem 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
Author
wangye
Source
Recommend
今天从基础开始学起,以为二分挺容易的,但是忽视了题目需要考虑时间复杂度,会不会爆int,等等。
存不存在ai,bi,ci加起来是x。
如果直接枚举那也太简单了吧,我就想着,大循环a,小循环b,小小循环对c二分,发现这样也超时!!!
然后,我就大循环a,小循环对b二分,小小循环对c二分,结果这样的思路是完全错的!!!
然后看看题解,要先把a+b的所有可能都存起来放到sum里,再大循环c,对sum二分。开始还觉得这个思路不是和我一开始的思路差不多吗?仔细一想,我大循环a,小循环b,一方面会有很多重复的a+b,重复带入算,费时,另一方面,每输入一个x,又要大循环啊,小循环b的,很费时。
#include <iostream> #include <stack> #include <string.h> #include <stdio.h> #include<queue> #include<algorithm> #define ll long long using namespace std; int a[505]; int b[505]; int c[505]; int sum[500005]; int main() { int L,N,M; int k=0; while(~scanf("%d %d %d",&L,&N,&M)) { k++; for(int i=1;i<=L;i++) { scanf("%d",&a[i]); } for(int i=1;i<=N;i++) { scanf("%d",&b[i]); } for(int i=1;i<=M;i++) { scanf("%d",&c[i]); } int n,x; printf("Case %d: ",k); scanf("%d",&n); int p=1; for(int i=1;i<=L;i++) { for(int j=1;j<=N;j++) { sum[p++]=a[i]+b[j]; } } sort(sum+1,sum+p); sort(c+1,c+1+M); while(n--) { scanf("%d",&x); bool f=0; for(int i=1;i<=M;i++) { if(sum[1]>x-c[i])//不能写成sum[1]+c[1]>x,因为可能会爆int break; int le=1;int ri=p-1; while(le<=ri) { int mid=(le+ri)/2; if(sum[mid]==x-c[i]) { f=1; break; } else if(sum[mid]>x-c[i]) { ri=mid-1; } else if(sum[mid]<x-c[i]) le=mid+1; } if(f) break; } if(f) printf("YES "); else printf("NO "); } } return 0; }
以上是关于HDU 2143 Can you find it?(基础二分)的主要内容,如果未能解决你的问题,请参考以下文章
HDU 2141 Can you find it? 二分查找
HDU 2141 Can you find it? (二分)