C语言实现分治法实例

2020-01-06 19:19:48于海丽

本文为大家分享了C语言实现分治法实例代码,供大家参考,具体内容如下

使用分治法求最大值

这个函数将数组a[l]...a[r]分成a[l],...,a[m]和a[m+1],...a[r]两部分,分别求出每一部分的最大元素(递归地),并返回较大的那一个作为整个数组的最大元素.如果数组大小是偶数,则两部分大小相等;如果是奇数,第一部分比第二部分的大小大1.


#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <malloc.h>
using namespace std;
#define OK 1
#define ERROR -1
#define TRUE 1
#define FALSE 0
typedef int Status;
 
int Max(int a[], int l, int r)
{
  int u, v, m = (l + r) / 2;
  //当区间中只有一个元素,递归终止,并将该元素返回
  if(l == r)
    return a[l];
  //递归原区域的左边
  u = Max(a, l, m);
  //递归原区域的右边
  v = Max(a, m+1, r);
  //返回最大值
  return (u>v)?u:v;
}
int main()
{
  //举例验证
  int a[7] = {6, 5, 3, 4, 7, 2, 1};
  int maxx = Max(a, 0, 6);
  printf("%dn", maxx);
  return 0;
}

汉诺塔的解

我们把盘子(递归地)移动到c上的方案是,将除了最下面的盘子之外的所有盘子移到b上,然后将做下面的盘子移到c上,然后(递归地)再将其他盘子移回到最下面的盘子上面.


#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <malloc.h>
using namespace std;
#define OK 1
#define ERROR -1
#define TRUE 1
#define FALSE 0
typedef int Status;
//输出盘子的移动
void shift(int n, char x, char y)
{
  printf("Move %d disk: %c ---------> %cn", n, x, y);
}
void hanoi(int n, char a, char b, char c)
{
  //递归终止的条件
  if(n == 1)
  {
    //将a上最下面的盘子移到c上
    shift(n, a, c);
    return;
  }
  //以c为中间轴,将a上的盘子移动到b上
  hanoi(n-1, a, c, b);
  shift(n, a, c);
  //以a为中间轴,将b上的盘子移动到c上
  hanoi(n-1, b, a, c);
}
int main()
{
  //举例验证
  hanoi(4, 'a', 'b', 'c');
  return 0;
}

使用分治法在尺子上画刻度