[CodeForces725 C. Hidden Word] 构造 + STL
题目链接:[CodeForces725 C. Hidden Word]
题意描述:
Let’s define a grid to be a set of tiles with 2 rows and 13 columns. Each tile has an English letter written in it. The letters don’t have to be unique: there might be two or more tiles with the same letter written on them. Here is an example of a grid:
A sequence of tiles is called a path if each tile in the sequence is adjacent to the tile which follows it (except for the last tile in the sequence, which of course has no successor). In this example, “ABC” is a path, and so is “KXWIHIJK”. “MAB” is not a path because ‘M’ is not adjacent to ‘A’. A single tile can be used more than once by a path (though the tile cannot occupy two consecutive places in the path because no tile is adjacent to itself).
You’re given a string s which consists of 27 upper-case English letters. Each English letter occurs at least once in s. Find a grid that contains a path whose tiles, viewed in the order that the path visits them, form the string s. If there’s no solution, print “Impossible” (without the quotes).
Input
The only line of the input contains the string s, consisting of 27 upper-case English letters. Each English letter occurs at least once in s.
Output
Output two lines, each consisting of 13 upper-case English characters, representing the rows of the grid. If there are multiple solutions, print any of them. If there is no solution print “Impossible”.
解题思路:
找到重复的两个字符,取中点截断。然后,随便搞搞就OK了。贴代码的主要原因是多熟悉一下stl和string的使用。
#include <bits/stdc++.h>
using namespace std;
string buf;
vector<string> Ans(2);
int main() {
cin >> buf;
char ch = 0;
for(int i = 1; i < 27; i++) if(buf[i] == buf[i - 1]) { cout << "Impossible\n"; return 0; }
vector<bool> vis(26, false);
for(int i = 0; i < 27; i++) {
int x = buf[i] - 'A';
if(vis[x]) ch = buf[i];
vis[x] = true;
}
int p[2];
p[0] = p[1] = -1;
for(int i = 0; i < 27; i++) {
if(buf[i] != ch) continue;
if(p[0] == -1) { p[0] = i; continue; }
if(p[1] == -1) { p[1] = i; break; }
}
int mid = (p[0] + p[1]) / 2;
for(int i = mid; i >= 0; i--) {
if(p[1] - mid >= mid - p[0] && buf[i] == ch) continue;
Ans[0] += buf[i];
}
for(int i = mid + 1; i < 27; i++) {
if(p[1] - mid < mid - p[0] && buf[i] == ch) continue;
Ans[1] += buf[i];
}
for(int k = 0; k < 2; k++) {
int len = Ans[k].length();
if(len <= 13) continue;
string str;
str.assign(Ans[k], 13, len - 13);
reverse(str.begin(), str.end());
Ans[k ^ 1] += str;
Ans[k].erase(13, len - 13);
}
copy(Ans.begin(), Ans.end(), ostream_iterator<string>(cout, "\n"));
return 0;
}