现在的位置: 首页 > 综合 > 正文

几种选择全排列实现的效率

2012年09月08日 ⁄ 综合 ⁄ 共 1078字 ⁄ 字号 评论关闭

统计几种选择全排列实现的效率,所谓选择全排列,如:在4个球之间选择2个球,其全排列数为 

代码如下:

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cmath>

using namespace std;
int cnt, cct, tot, n, k;
char a[25];
void test_1(int cur)
{
    if(cnt == k)
    {
        ++tot;
        return ;
    }
    else if(cur == n)
    {
        ++cct;
        return ;
    }
    ++cnt;
    test_1(cur + 1);
    --cnt;
    test_1(cur + 1);
}
void test_2(int cur)
{
    if(n - cur < k - cnt)
    // 剪枝,剩下的数的个数小于所需的1的个数时,不需要继续往下走了,直接返回
    {
        ++cct;
        return ;
    }
    if(cnt == k)
    {
        ++cct;
        return ;
    }
    else if(cur == n)
    {
        ++cct;
        return ;
    }
    ++cnt;
    test_2(cur + 1);
    --cnt;
    test_2(cur + 1);
}
void test_3(int cur)
{
    if(n - cur < k - cnt)
    {
        ++cct;
        return ;
    }
    if(cur == n)
    {
        ++cct;
        return ;
    }
    if(cnt <= k)
    {
        ++cnt;
        test_3(cur + 1);
        --cnt;
        test_3(cur + 1);
    }
    else
        test_3(cur + 1);
}
int main()
{
    n = 16; // 样本总个数
    k = 1;  // 选择出的个数
    printf("%d 个数的全排列的总个数为:%d.\n", n, (int)pow(2, n));

    tot = cnt = cct = 0;
    test_1(0);
    printf("%d 个里面选 %d个的全排列的总个数 %d.\n", n, k, tot);
    printf("一般回溯法的实际运行次数为:%10d, ", cct + tot);
    printf("效率 :%.4lf%%。\n", (double)tot / (double)(cct + tot) * 100);

    cnt = cct = 0;
    test_2(0);
    printf("剪枝优化后的实际运行次数为:%10d, ",  cct);
    printf("效率 :%.4lf%%.\n",  (double)tot / (double)cct * 100);

    cct = cnt = 0;
    test_3(0);
    printf("剪枝优化后的实际运行次数为:%10d, ",  cct);
    printf("效率 :%.4lf%%.\n",  (double)tot / (double)cct * 100);
}

抱歉!评论已关闭.