﻿ C语言实现分治法实例 - 鸿网互联

# 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;

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("%d\n", maxx);
return 0;
}```

```#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 ---------> %c\n", 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;
}```

```#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 mark(int m, int h)
{
//由于无法实际表示刻度线之间的高度差,故用实际数字来体现
printf("%d ", h);
}
//划分该区域内的刻度
void rule(int l, int r, int h)
{
//找到该区域的中间
int m = (l + r) / 2;
//当高度大于0
if(h)
{
//划分小区域
rule(l, m, h-1);
//画线
mark(m, h);
//划分小区域
rule(m+1, r, h-1);
}
}
int main()
{
//举例验证
rule(0, 14, 4);
return 0;
}```

<