题目链接:http://csoj.scnu.edu.cn/contest/102/problem/1005
解题思路:
代码如下:
#include<iostream>
#include<math.h>
#include<algorithm>
using namespace std;
const int N = 1e5 + 10;int s[N], l, r;
int now;int findl(int now)
{for (int i = l; i <= r; i++){if (s[i] != now) return i; now ^= 1;}return -1;
}int findr(int now)
{for (int i = r; i >= l; i--){if (s[i] != now) return i;now ^= 1;}return -1;
}
int main()
{ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);int T;cin >> T;while(T--){int n;cin >> n;string t;cin >> t;for (int i = 1; i <= n; i++)s[i] = t[i - 1] & 1;//找到谁第一次拿到主动权l = 1, r = n;now = 0;while(s[l] != s[r] && l < r){if (s[l] == now) l++;else if (s[r] == now) r--;now ^= 1;}if (l == r && s[l] == now){cout << "-1" << endl;continue;}if (s[l] != now){now ^= 1;cout << now << endl;continue;}int lpos = findl(now); //从左边找到出现连续两个的最近位置 int rpos = findr(now);if ( (lpos != -1 && s[lpos] == now) || (rpos != -1 && s[rpos] == now) )cout << now << endl;else if (lpos - 1 == rpos || lpos == -1) //特判只有一个!x!x的情况 cout << "-1" << endl;else cout << s[lpos] << endl;//没有xx序列 且有多个!x!x }return 0;
}