• 【算法】 取火柴


    真的太笨了。

    我!

    这个道理和编程无关,每人最多取4根,
    1+4=5
    21=5*4+1
    也就是说,只要保证每轮两方之和是5,那么4轮后取走20根,最后先取的人必定取最后一根。

    第二题:需要用递推的方式,计算所有必胜必输的状态,然后保证每次取火柴都让对方到达必输状态。
    所谓必输就是只剩最后一根,或者无论怎么取后的结果都是必胜。

    大致的思路是:你拿n根(1<=n<=4)火柴,电脑就拿5-n根火柴,只要保证每回合内,你拿的火柴根数+电脑拿的火柴根数=5,四个回合后,一共拿走20根火柴,肯定还剩1根,那必须是你自己拿,于是电脑就赢了!
    #include<stdio.h>
     
    void main()
    {
        int s=21,t;
        int n;
        printf("比赛开始!
    ");
        do
        {
            if(s==1) 
            {
                printf("你必须拿最后一根火柴!
    ");
                break;
            }
            printf("你想要拿几根火柴(1~4)?");
            scanf("%d",&n);
            while(1)
            {
                if(n>=1&&n<=4)
                {
                    break;
                }
                printf("只能取1~4根火柴哦!
    请重新输入:");
                scanf("%d",&n);
            }
            s=s-n;
            if(s==0) 
            {
                break;
            }
            printf("还剩%d根火柴
    ",s);
            printf("电脑拿了%d根火柴
    ",5-n);
            s=s-(5-n);
            printf("还剩%d根火柴
    ",s);
        }while(s);
        printf("电脑获胜!
    ");
    }
    #include <stdio.h>
    #include <stdlib.h>
     
    void fun()
    {
        int hcs = 21,czs = 0;
        int count;
        while(hcs > 0)
        {
            printf("Now %d
    ",hcs);
            if(0 == czs % 2) //
            {
                do
                {
                    printf("Person:");
                    scanf("%d",&count);
                
                }while(count <= 0 || count > 4);
                hcs = hcs - count;
            }
            else  // 电脑操作
            {
                count = (hcs - 1) % 5;  //为了凑齐 5 这个数字 不减一 会 多增加一个
                printf("Computer:%d
    ",count);
                hcs = hcs - count;
            }
            czs++;
        }
    }
    void  main()
    {
        fun();
     
    }
  • 相关阅读:
    Java运行时内存
    java --对象流与对象的序列化
    Java 文件操作
    爬虫
    eclipse项目放到github
    越来越玄的JAVA
    map和set的遍历
    集合总览
    unsafe类
    狡诈的java并发容器
  • 原文地址:https://www.cnblogs.com/paprikatree/p/10511567.html
Copyright © 2020-2023  润新知