• [Locked] Flip Game I & II


    Flip Game I

    You are playing the following Flip Game with your friend: Given a string that contains only these two characters:+and -, you and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move and therefore the other person will be the winner.

    Write a function to compute all possible states of the string after one valid move.

    For example, given s = "++++", after one move, it may become one of the following states:

    [
      "--++",
      "+--+",
      "++--"
    ]
    

    If there is no valid move, return an empty list [].

    分析:

      一层处理即可

    代码:

    vector<string> flipGame(string str) {
        vector<string> vs;
        for(int i = 0; i < str.length() - 1; i++) {
            if(str[i] == '+' && str[i + 1] == '+') {
                str[i] = str[i + 1] = '-';
                vs.push_back(str);
                str[i] = str[i + 1] = '+';
            }
        }
        return vs;
    }

    Flip Game II

    You are playing the following Flip Game with your friend: Given a string that contains only these two characters: + and -, you and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move and therefore the other person will be the winner.

    Write a function to determine if the starting player can guarantee a win.

    For example, given s = "++++", return true. The starting player can guarantee a win by flipping the middle "++" to become "+--+".

    Follow up:
    Derive your algorithm's runtime complexity.

    分析:

      第一想法是找到合适的规律,可以直接从当前状态判断是否必胜,经过尝试,难以直接判断;所以采用一般解法,当两边都是没有失误的高手状态下,有以下规律:

        1、终结点是必败点(P点);

        2、从任何必胜点(N点)操作,至少有一种方法可以进入必败点(P点)

        3、无论如何操作, 从必败点(P点)都只能进入必胜点(N点).

      这里用到的就是1,2,3规律,对手无点可操作,则以失败终结;自己必胜,则至少一种方法进入下一轮必败点;若不能必胜,则找不到方法进入下一轮必败点;若自己必败,则无论用什么方法下一轮都是必胜点。

    代码:

    bool canwin(string str) {
        for(int i = 0; i < str.length() - 1; i++) {
            if(str[i] == '+' && str[i + 1] == '+') {
                str[i] = str[i + 1] = '-';
                int win = !canwin(str);
                str[i] = str[i + 1] = '+';
                if(win)
                    return true;
            }
        }
        return false;
    }
  • 相关阅读:
    【洛谷5052】[COCI2017-2018#7] Go(区间DP)
    【洛谷6564】[POI2007] 堆积木KLO(树状数组优化DP)
    【洛谷6940】[ICPC2017 WF] Visual Python++(扫描线)
    【洛谷6939】[ICPC2017 WF] Tarot Sham Boast(PGF结论题)
    【洛谷4123】[CQOI2016] 不同的最小割(最小割树)
    初学最小割树
    【洛谷6122】[NEERC2016] Mole Tunnels(模拟费用流)
    【洛谷6936】[ICPC2017 WF] Scenery(思维)
    【洛谷2805】[NOI2009] 植物大战僵尸(最大权闭合子图)
    【洛谷1393】Mivik 的标题(容斥+border性质)
  • 原文地址:https://www.cnblogs.com/littletail/p/5199634.html
Copyright © 2020-2023  润新知