分治
早在几百年前,我国的古书《群经平议·周官二》里就有记载:“分而治之”的思想。
数学归纳法与递归思想
L. Peter Deutsch 这句话的意思是:“迭代的是人,递归的是神”。
归并排序
在本世纪的前十几年里,pascal 时信息学竞赛的主流,由于没有 stl 和很多其他库函数的帮助,pascal 中必须手写一些数据结构和算法,归并排序就是当年没有 sort 时,选手们常写的一种排序。
在这里拿归并先讲,主要原因是它是一个十分简单、易于理解、具有代表性的分治应用。
归并排序的思路是:当给一个数组排序的时候,先将数组分为两段,然后对两段分别进行归并排序,当分隔到每段长度为
#include <bits/stdc++.h>
using namespace std;
const int N = 100005;
int a[N];
int zc[N];
void msort(int a[], int st, int ed) {
if (st == ed) return;
int mid = (st + ed) >> 1;
msort(a, st, mid), msort(a, mid + 1, ed);
for (int i = st, j = mid + 1, k = 1; k <= ed - st + 1; ++k)
if (i > mid) zc[k] = a[j], ++j;
else if (j > ed) zc[k] = a[i], ++i;
else if (a[i] > a[j]) zc[k] = a[j], ++j;
else zc[k] = a[i], ++i;
for (int i = 1, j = st; j <= ed; ++i, ++j)
a[j] = zc[i];
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int n;
cin >> n;
for (int i = 1; i <= n; ++i) cin >> a[i];
msort(a, 1, n);
for (int i = 1; i <= n; ++i) cout << a[i] << ' ';
return 0;
}
扩展:偏序问题与 cdq 分治,有兴趣可以去读一读。