设为首页 加入收藏

TOP

C语言排序--Can you find it?(Hdu 2141)
2015-01-21 11:09:17 来源: 作者: 【 】 浏览:14
Tags:语言 排序 --Can you find Hdu 2141
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

题目大意: 输入数据第一排是三个数,分别表示三个数组的大小. (三个数组的大小的最大值都是500) 接下来的三排是输入三个数组的数字. 然后第四排输入一个整数n表示接下来n排测试数据. 每个测试数据是一个整数m. 要求在上面的三个数组中每个数组找一个数(共三个数)相加之和等于该测试数据m.如果找到了就输出YES,如果不存在这样的三个数那么就输出NO.

大致思路:
因为题目给的数据每个数组最多有500个元素,那么如果三个for循环就是500*500*500肯定超时,(姑且我们这里把第一第二第三数组叫为a,b,c数组) 这个时候我们可以把c数组排序,然后用两个for循环枚举a,b两个数组中所有组合的和k,然后再用二分查找在c数组中查找m-k这个数.这样时间最多为500*500*log500≈2250000 或者是在a,b两个数组中所有组合的和k组成的数组中去二分查找m-c[i]这个数(以下代码便是).
代码如下:
#include 
  
   
#include 
   
     using namespace std; int a[501],b[501],m[250001],c[501],flag; void find(int a[],int b,int n) { int left,right,mid; left=0,right=n-1; while(left<=right) { mid=(left+right)/2; if(a[mid]==b) { flag=1; break; } else if(a[mid]>b) right=mid-1; else left=mid+1; } } int main() { int i,j,k,n1,n2,n3,n4,ci=0; while(scanf("%d%d%d",&n1,&n2,&n3)!=EOF) { ci++; for(i=0;i
     
    
   
  
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C语言贪心-最少拦截系统(Hdu 1257) 下一篇C语言,python和Javascript的实现

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: