2007-08-22

    枚举法 - [Algorithms]

    版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
    http://conoon.blogbus.com/logs/7858114.html

    有4个学生,上地理课时提出我国四大谈水湖的排列次序如下:

    甲:洞庭湖最大,洪泽湖最小,鄱阳湖第三;

    乙:洪泽湖最大,洞庭湖最小,鄱阳湖第二,太湖第三;

    丙:洪泽湖最小,洞庭湖第三;

    丁:鄱阳湖最大,太湖最小,洪泽湖第二,洞庭湖第三;

       对于各湖泊应处的位置,每个人只说对了一个。根据以上描述和条件,编写程序,让计算机判断一下各湖泊应该处于第几位。

     

    解题思路:设置洞庭湖、洪泽湖、鄱阳湖、太湖分别用字母A、B、C、D代表,最大到最小依次用数字4——1表示。应用枚举法可以解决此问题,不过稍微复杂罗嗦点。

    源程序如下:

    program hupo;
    var
      a,b,c,d:integer;
    begin
      for b:=1 to 4 do
        for a:=1 to 4 do
          if ((b=1) and (a<>2)) or ((a=2) and (b<>1)) then
           if a<>b then
           for c:=1 to 4 do
             if (a<>c) and (b<>c) then
              if (a+b+c<>7) and (a+b<>5) and (a+c<>6) and (b+c<>3) then
              for d:=1 to 4 do
               if c<>d then
                if  (b+a<>5) and (b+c<>7) and (b+d<>6) then
                   if (a+c<>4) and (a+d<>3) and (c+d<>5) then
                     if (c+d<>5) and (c+b<>7) and (c+a<>6) then
                       if (d+b<>4) and (d+a<>3) and (b+a<>5) then
                            writeln('a=',a,' b=',b,' c=',c,' d=',d)

    end.

    改进程序:

    program ygzj;
    var
    a,b,c,d:integer;
    begin
    for a:=1 to 4 do
      for b:=1 to 4 do
        for c:=1 to 4 do
         begin
          d:=10-a-b-c;
          if ord(a=1)+ord(b=4)+ord(c=3)=1 then
            if ord(b=1)+ord(a=4)+ord(c=2)+ord(d=3)=1 then
              if ord(b=4)+ord(a=3)=1 then
                if ord(c=1)+ord(d=4)+ord(b=2)+ord(a=3)=1 then
                  if a*b*c*d=24 then
                  writeln('洞庭湖第':3,a:3,'洪泽湖第':3,b:3,'波阳湖第':3,c:3,'太湖第':3,d:3);
          end;
    writeln
    end.


    收藏到:Del.icio.us




    Tag:
    引用地址:

发表评论

您将收到博主的回复邮件
记住我