现在的位置: 首页 > 综合 > 正文

杭电2141

2014年09月05日 ⁄ 综合 ⁄ 共 1958字 ⁄ 字号 评论关闭

          

                          Can you find it?

                                                    Time Limit: 10000/3000 MS (Java/Others)    Memory Limit: 32768/10000 K (Java/Others)
                                                                   Total Submission(s): 3988    Accepted Submission(s): 997

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
 
在做此题的时候,如果单纯的用多重循环来实现会超时,正确的思路是先合并数组+排序+二分查找。下面是我的代码:
 
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a,const void *b)
{
	return (*(int *)a-*(int *)b);
}
int  main()
{
	int f(int a[500*500],int x,int y,int z);
	int i,j,m,n,s,t,x,y,z,k;
	int a[500],b[500*500],c[500],d[1000];
	z=1;
	while(scanf("%d %d %d",&n,&m,&t)!=EOF)
	{
		y=0;
		for(i=0;i<=n-1;i++)
		{
			scanf("%d",&a[i]);
		}
		for(i=0;i<=m-1;i++)
		{
			scanf("%d",&x);
			for(j=0;j<=n-1;j++)
			{
				b[y]=a[j]+x;
				y+=1;
			}
		}
		for(i=0;i<=t-1;i++)
		{
			scanf("%d",&c[i]);
		}
		scanf("%d",&x);
		for(i=0;i<=x-1;i++)
		{
			scanf("%d",&d[i]);
		}
		qsort(b,n*m,sizeof(b[0]),cmp);
		printf("Case %d:\n",z);
		for(i=0;i<=x-1;i++)
		{
			for(j=0;j<=t-1;j++)
			{
				s=d[i]-c[j];
				k=f(b,0,n*m-1,s);
				if(k==1)
				{
					break;
				}
			}
			if(j==t)
			{
				printf("NO\n");
			}else
			{
				printf("YES\n");
			}
		}
		z+=1;
	}
	return 0;
}
int f(int a[500*500],int x,int y,int z)
{
	int k,mid;
	k=0;
	while(x<=y)
	{
		mid=(x+y)/2;
		if(a[mid]==z)
		{
			k=1;
			break;
		}else if(a[mid]>z)
		{
			y=mid-1;
		}else
		{
			x=mid+1;
		}
	}
	return (k);
}

 

                    

抱歉!评论已关闭.