实验3 分治算法实验一

这篇博客主要介绍了分治算法的应用,包括使用非递归和递归实现二分搜索,实现时间复杂度为O(n)的数组合并,二路归并排序的代码实现,以及棋盘覆盖问题的解决。同时,还涵盖了快速排序的编程实现,探讨了其基本思想。
摘要由CSDN通过智能技术生成

实验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>
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值