Game with string CodeForce#1104B 栈、串

题目链接:Game with string

题目原文

Two people are playing a game with a string 𝑠s, consisting of lowercase latin letters.

On a player's turn, he should choose two consecutive equal letters in the string and delete them.

For example, if the string is equal to "xaax" than there is only one possible turn: delete "aa", so the string will become "xx". A player not able to make a turn loses.

Your task is to determine which player will win if both play optimally.

思路

很显然,假设可以删掉的'xx'的个数是奇数则先手玩家胜,若为偶数则后手玩家胜。

所以问题转化为求解s中可以删掉的xx'的个数。如果用模拟的话,估计会超时。遇到这种部分回文的序列,用栈来处理就方便很多了。把字符串s里的字符依次入栈,如果s[i]和栈顶元素相同,就出栈,同时ans++,最后判断ans的奇偶性即可。

题解

 1 #include <iostream>
 2 #include <cstring>
 3 #include <stack>
 4 
 5 using namespace std;
 6 
 7 stack<char> s;
 8 string str;
 9 
10 int main(int argc, char const *argv[])
11 {
12     cin >> str;
13     int ans = 0;
14     for(int i = 0; i < str.length(); i++)
15     {
16         if(!s.empty() && str[i] == s.top())
17         {
18             ans++;
19             s.pop();
20         }
21         else
22         {
23             s.push(str[i]);
24         }
25     }
26     if(ans % 2 == 0)
27     {
28         cout << "No" << endl;
29     }
30     else
31     {
32         cout << "Yes" << endl;
33     }
34     return 0;
35 }

 

posted @ 2019-01-23 17:50  SaltyFishQF  阅读(813)  评论(0编辑  收藏  举报