Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4059
  • 博文数量: 3
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 52
  • 用 户 组: 普通用户
  • 注册时间: 2013-05-22 22:30
文章分类
文章存档

2013年(3)

我的朋友

分类: C/C++

2013-07-03 10:54:25

今天遇见一道题目是这样的:5位运动员参加了跳水比赛,有人让他们预测比赛结果。
A选手说: B第一,我第四。
B选手说: 我第二,E第四。
C选手说: 我第一,D第二。
D选手说: C最后,我第三。
E选手说: 我第四,A第一。
比赛结束后,每位选手都说对了一半,请编程确定比赛的名次。

这里面需要用到一个全排列的算法,我不会,于是上网搜到了一个,这个算法太牛,我用gdb调试器next和step了好久,只能隐约明白它是怎么执行的……那人给出来的程序还不全,其中用到的swap函数没有,害得我自己写了一个。

程序如下

#include
#include

void permutate(char* str, int begin, int end)
{
      int i;
      if(begin == end)
      {
        printf("\n%s",str);
        if(((str[0]=='B')+(str[3]=='A')==1)&&((str[1]=='B')+(str[3]=='E')==1)&&((str[0]=='C')+(str[1]=='D')==1)&&((str[4]=='C')+(str[2]=='D')==1)&&((str[3]=='E')+(str[0]=='A')==1))
        printf("-----------------found!");
        
      }
      else
      {
         for(i=begin; i           {
            swap(str+begin,str+i);
            permutate(str, begin+1, end);
            swap(str+begin,str+i);            
          }               
      }     
}
void swap(char* letter1,char* letter2)
{
    char* p=letter1;
    char* q=letter2;
    char temp;
    temp=*p;
    *p=*q;
    *q=temp;
}

int main()
{
    char abcde[]="ABCDE";
    permutate(abcde,0,5);
    return 0;
}    


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

上一篇:好乱好乱好乱好乱!

下一篇:没有了

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