题意:
Alice有
张石头牌、
张剪刀牌、
张布牌,
Bob有
张石头牌、
张剪刀牌、
张布牌,
你可以随意安排出牌策略,问你Alice最多可以胜Bob多少回?
解法一(暴力模拟)
题目叫我们求获胜的次数,故我们只考虑获胜的情况。
1. Alice出石头:
我们此时让Bob出剪刀
2. Alice出剪刀
我们此时让Bob出布
3. Alice出布
我们此时让Bob出石头
故当
都不为0时,我们每次让
同时减一,然后答案加一
当
都不为0时,我们每次让
同时减一,然后答案加一
当
都不为0时,我们每次让
同时减一,然后答案加一
代码:
class Solution { public: int Mostvictories(int n, int p1, int q1, int m1, int p2, int q2, int m2) { int ans=0;//最终答案 while(p1>0&&q2>0){ p1--,q2--;//石头对剪刀 ans++; } while(q1>0&&m2>0){ q1--,m2--;//剪刀对布 ans++; } while(m1>0&&p2>0){ m1--,p2--;//布对石头 ans++; } return ans; } };时间复杂度:
空间复杂度:
,程序中并没有申请额外的内存,故空间复杂度为
解法二(直接计算)
我们先只考虑Alice出石头,Bob出剪刀的一种情况:
1. 
显然这种情况获胜的次数为
2. 
显然这种情况获胜的次数为
或
3. 
显然这种情况获胜的次数为
综上所述,这种情况获胜的次数为
其他两种情况同理,获胜次数分别为
和
代码:
class Solution { public: int Mostvictories(int n, int p1, int q1, int m1, int p2, int q2, int m2) { return min(p1,q2)+min(q1,m2)+min(m1,p2);//石头对剪刀、剪刀对布、布对石头 } };时间复杂度:
空间复杂度:
,程序中没有申请额外的内存,故空间复杂度为)