您的位置:首页 > 其它

CodeForce 525B Pasha and String(字符串)

2015-04-19 08:51 351 查看
Pasha and Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string.Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent m days performing the following transformations on his string — each day he chose integer ai and reversed a piece of string (a segment) from position ai to position|s| - ai + 1. It is guaranteed that 2·ai ≤ |s|.You face the following task: determine what Pasha's string will look like after m days.InputThe first line of the input contains Pasha's string s of length from 2 to 2·105 characters, consisting of lowercase Latin letters.The second line contains a single integer m (1 ≤ m ≤ 105) — the number of days when Pasha changed his string.The third line contains m space-separated elements ai (1 ≤ ai; 2·ai ≤ |s|) — the position from which Pasha started transforming the string on the i-th day.OutputIn the first line of the output print what Pasha's string s will look like after m days.Sample test(s)input
abcdef
1
2
output
aedcbf
input
vwxyz
2
2 2
output
vwxyz
input
abcdef
3
1 2 3
output
fbdcea
题意:给出一个长度不超过2*10^5的字符串,进行m次反转。每次反转第a个到第len-a+1个字符之间这一段。求经过m次反转后的字符串是什么。其中len 为字符串的长度。分析:如果直接按照题意描述进行模拟,复杂度为O(len*m),肯定会TLE,所以我们要寻找高效的办法。对于第i个字符,只有它之前的字符(包括自己)需要反转时,才会引起第i个字符的位置改变。所以我们只需要判断第i个字符的位置一共变了多少次,如果是奇数次,就让它改变位置;否则位置不变。这样复杂度为O(len),完全可以接受。
#include <iostream>
#include <string>
#include <map>
#include <cstdio>
#include <algorithm>
using namespace std;

int main() {
    int m, a;
    string str;
    while(cin >> str >> m) {
        map <int, int> mp; // 记录i出现了多少次
        while(m--) {
            cin >> a;
            if(!mp[a]) mp[a] = 1;
            else mp[a]++;
        }
        int sum = 0; // 第i个字符需要变换的次数
        int len = str.length();
        for(int i = 0; i < len / 2; i++) {
            sum += mp[i + 1];
            if(sum & 1)
                swap(str[i], str[len - 1 - i]);
        }
        cout << str << endl;
    }
    return 0;
}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: