实验3 分治算法实验一
OJ练习
1. 素数判定:http://acm.hdu.edu.cn/showproblem.php?pid=2012
2. 蟠桃记:http://acm.hdu.edu.cn/showproblem.php?pid=2013
3. 偶数求和:http://acm.hdu.edu.cn/showproblem.php?pid=2015
4. Can you find it?:http://acm.hdu.edu.cn/showproblem.php?pid=2141
5. 数列有序!:http://acm.hdu.edu.cn/showproblem.php?pid=2019
6. 绝对值排序:http://acm.hdu.edu.cn/showproblem.php?pid=2020
7*. Toxophily:http://acm.hdu.edu.cn/showproblem.php?pid=2298
8*. Turn the corner:http://acm.hdu.edu.cn/showproblem.php?pid=2438
9*. Quoit Design:http://acm.hdu.edu.cn/showproblem.php?pid=1007
10*. Can you solve this equation?:
http://acm.hdu.edu.cn/showproblem.php?pid=2199
11*. Pie:http://acm.hdu.edu.cn/showproblem.php?pid=1969
12*. Cup:http://acm.hdu.edu.cn/showproblem.php?pid=2289
实验内容
1. 二分搜索。分别使用非递归算法和递归算法实现二分搜索。【输入:一个一维整型数组和一个待查询的值;输出:待查询值所在的位置,如果没有找到,则返回-1。】
源代码(非递归算法):
#include<iostream>
#include<cstdio>
#include<string>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<cstring>
#include<algorithm>
#define rep(i,a,b) for(int i=(a);i<(b);i++)
#define rev(i,a,b) for(int i=(a);i>=(b);i--)
#define clr(a,x) memset(a,x,sizeof a)
#define inf 0x3f3f3f3f
typedef long long LL;
using namespace std;
const int mod=1e9 +7;
const int maxn=2005;
const int maxm=4005;
int a[maxn],tmp[maxn];
int ans;
int BinarySort(int a[], int n, int l, int r)
{
while(l <= r)
{
int mid = l + (r - l)/2;
if(l > r) return -1;
if(n == a[mid]) return mid;
if(n > a[mid]) l = mid + 1;
else if(n < a[mid]) r = mid - 1;
}
return -1;
}
int main()
{
int n, x;
cin>>n;
for(int i=1; i<=n; i++) cin>>a[i];
cin>>x;
printf("%d\n",BinarySort(a,x,1,n));
return 0;
}
源代码(递归算法):
#include<iostream>
#include<cstdio>
#include<string>
#include<cmath>
#include<queue>
#include<stack>