前提条件:有一组数已经按从小到大(或从大到小)排序
递归法的程序代码:
目标:输入一个数x,在这组数查找是否有x
迭代法的程序代码:
#include<stdio.h>
#define N 10
int find(int a[ ], int x, int bott, int top);
void main( )
{ int i, x, a[N], result;
printf("\n 输入数组 a:\n");
for(i=0; i<N; i++) scanf("%d", &a[i]);
printf(“输入要查找的数 x:");
scanf("%d", &x);
result=find(a, x, 0, N-1);
if (result== -1) printf("%d is not found.\n", x);
else printf("Find %d==a[%d]\n", x, result);
}
int find(int a[ ], int x, int bott, int top)
{ int mid;
while(bott<=top)
{ mid=(bott+top)/2;
if(x==a[mid])
return(mid);
else
if(x<a[mid])
top=mid-1;
else bott=mid+1;
}
return(-1);
}
递归法的程序代码:
nt find(int a[ ], int x, int bott, int top)
{ int mid;
if(bott<=top)
{ mid=(bott+top)/2;
if(x==a[mid])
else
if(x<a[mid])
else
}
}
题目: hdu 2199 2141 1597 4004 2446(可以用)
hdu 2141代码:
#include<iostream>
#include<algorithm>
#define size 251000
using namespace std;
__int64 a[size], s1[610] , s2[610] , s3[610];
int k;
int find(int low , int heigh , __int64 temp)
{
int m;
if(low < heigh )
{
m = (low + heigh)/2;
if( a[m] == k - temp ) return 1;
else if( a[m] < k - temp ) return find( m+1 , heigh , temp);
else return find( low , m , temp);
}
return 0;
}
int main()
{
int l,n,m,s;
int t=0,no;
while (scanf("%d%d%d",&l,&n,&m)!=EOF)
{
no=-1;
for(int i=0;i<l;i++) scanf("%I64d",&s1[i]);
for(int i=0;i<n;i++) scanf("%I64d",&s2[i]);
for(int i=0;i<m;i++) scanf("%I64d",&s3[i]);
for(int i=0;i<l;i++)
{
for(int j=0;j<n;j++)
{
a[++no] = s1[i] + s2[j];
}
}
sort(a,a+no);
scanf("%d",&s);
printf("Case %d:\n",++t);
for(int i=0;i<s;i++)
{
int flag = 0;
scanf("%d",&k);
for(int i = 0; i<m; i++)
{
if(find(0,no,s3[i]))
{
flag = 1;
break;
}
}
if(flag == 1) printf("YES\n");
else printf("NO\n");
}
}
return 0;
}