Chinaunix首页 | 论坛 | 博客
  • 博客访问: 54333
  • 博文数量: 16
  • 博客积分: 650
  • 博客等级: 上士
  • 技术积分: 170
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-08 19:32
文章分类

全部博文(16)

文章存档

2008年(16)

我的朋友
最近访客

分类: C/C++

2008-08-29 01:30:21

一共有上下两排数,上排的十个数是【0,1,2,3,4,5,6,7,8,9】
针对上排的每个数,在其对应的下面位置填写一个数,该数表示其在下面出现的次数。
如:
数值:0,1,2,3,4,5,6,7,8,9
分配:6,2,1,0,0,0,1,0,0,0
 
 

#include <iostream>

using namespace std;

const int N = 10;
int source[N];
int dest[N] = {0};

void init()
{
    for(int i=0; i<N; i++)
    {
        source[i] = i;
    }
}

void display(int target[])
{
    for(int i=0; i<N; i++)
    {
        printf("%4d", target[i]);
    }
    cout << endl;
}

int execute()
{
    int edit = 0;
    
    for(int i=0; i<N; i++)
    {
        int temp = 0;
        for(int j=0; j<N; j++)
        {
            if(dest[j] == source[i])
            {
                temp++;
            }
        }
        if(temp == dest[i])
        {
            
        }
        else
        {
            edit++;
            dest[i] = temp;
        }
    }
    return edit;
}

void main()
{
    int edit = 1,counts = 0;
    init();
    display(source);
    while(edit)
    {
        counts++;
        edit = execute();
        //display(dest); 打印每次执行后的轨迹

        if(counts > N + 1)
        {
            cout << "无解" << endl;
            break;
        }
    }
    display(dest); // 最后结果

}

原理很简单,就是对dest[]不停的遍历,有edit作为标志位,如果edit=0,则表示dest[]已经平衡了,跳出循环。

不过对于无解的情况,直接给出的就是整个遍历次数大于N+1,没有证明过,应该没问题

 

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

上一篇:从M个数中选N个

下一篇:没有了

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