Chinaunix首页 | 论坛 | 博客
  • 博客访问: 252555
  • 博文数量: 3
  • 博客积分: 2518
  • 博客等级: 少校
  • 技术积分: 520
  • 用 户 组: 普通用户
  • 注册时间: 2006-11-23 10:41
文章存档

2008年(3)

我的朋友

分类:

2008-06-12 22:58:50

在某杂志上看到这么一道算法题。。。用FLASH实现了一下。。主要为了练练没学多久的AS3。。 算法实现先用C写了一遍, 再用AS3改写了一遍。。。orz
代码及其丑陋。。AS就不拿出来了。文后附上用C写的代码。




#include "stdio.h"

int max_already = 0;
int result[1000];
int tmp_result[1000];
int search_count = 0;

int min(int n, int lb[]) {
    int i;
    int flag = 0;
    int t;
    int ret = 0;
    for (i=0; i<n;i++) {
        if (i == 0) {
            ret++;
            continue;
        }

        t = lb[i] - lb[i-1];
        if (flag == 0) {
            if (t == 1 || t == -1) {
                flag = t;
            } else {
                ret++;
            }
        } else if (flag == 1) {
            if (t == 1 ) {
                               
            } else {
                ret++;
                flag = 0;
            }
        } else if (flag == -1) {
            if (t == -1 ) {
                               
            } else {
                ret++;
                flag = 0;
            }
        }
    }
    return ret - 1;
}

int max(int n, int lb[]) {
    return 2 * (n-1);
}

int is_sorted(int n, int lb[]) {
    return min(n, lb) == 0 ? 1 : 0;
}

void revert(int n, int lb[], int f, int t) {
    int i, j;
    int value;
    for (i=f, j=t; i<j; i++, j--) {
        value = lb[i];
        lb[i] = lb[j];
        lb[j] = value;
    }
}

void search(int n, int already, int lb[]) {
    
    int estimate, i, j;
    estimate = min(n, lb);
    search_count++;
    if (estimate + already > max_already) {
        return;
    }

    if (is_sorted(n, lb)) {
        if (n > 1 && lb[1] < lb[0]) {
            tmp_result[already] = n-1;
            already++;
        }
        if (already < max_already) {
            max_already = already;
            //printf("find another %d\n", max_already);

            for(i=0; i<max_already;i++) {
                result[i] = tmp_result[i];
            }
        }
        return;
    }

    for (i=n-1;i>=0;i--) {
        revert(n, lb,0, i);
        tmp_result[already] = i;
        search(n, already+1, lb);
        revert(n, lb, 0, i);
    }


}


void main() {
    int n;
    int lb[1000];
    int i;
    scanf("%d", &n);
    for (i=0;i<n;i++) {
        scanf("%d", &lb[i]);
    }
    max_already = max(n, lb);
    //printf("run...\n");

    search(n, 0, lb);
    printf("searrch %d times..result: at least %d times \n", search_count,max_already);
    for(i=0; i<max_already;i++) {
        printf("%d\n", result[i]);
    }
}

阅读(2011) | 评论(0) | 转发(0) |
0

上一篇:纸上谈兵: 设计模式读书笔记

下一篇:没有了

给主人留下些什么吧!~~