ZUFE(周赛) 2326 交换字母(STL)

Time Limit: 1 Sec  Memory Limit: 128 MB

Description

有一个长度为n的字符串(只包含小写字母),操作m次,每次操作交换两个字母,输出最终字符串。

Input

多组输入,每组第一行为n,m表示字符串长度和操作数,1<n,m<=100000
第二行为长度n的字符串,接下来m行,每行两个字符,中间空格隔开,表示要交换的两个字符。

Output

每组数据输出一行,表示最终字符串。

Sample Input

5 1
lehho
h l
11 6
abacabadaba
a b
b c
a d
e g
f a
b b

Sample Output

hello
cdcbcdcfcdc

HINT

In the second sample the name of the corporation consecutively changes as follows:


abacabadaba-->babcbabdbab
babcbabdbab-->cacbcacdcac
cacbcacdcac-->cdcbcdcacdc
cdcbcdcacdc-->cdcbcdcacdc
cdcbcdcacdc-->cdcbcdcfcdc
cdcbcdcfcdc-->cdcbcdcfcdc

题解:如果用一般的方法,也就是真正去交换,数据中给出100000的字符串的话一定会TLE,那么就想到了用数组去保存每种字母的index,这样不必每次输入两个字符都要循环一次。但是,即使这样,刚开始的想法是,交换两个数组的内容,并且修改字符串,说到底实际上还是修改了字符串,所以超时。后来发现,根本不需要每一次都去改变字符串的内容,只要输出的时候改变就好了。

所以,思路是:使用26个数组,先循环一遍字符串,分别保存26个字母的索引(因为用的是string,所以保存的是迭代器),然后,每读取两个字母,就交换(使用swap函数)两个数组,这里v[0]就是‘a',v[1]就是’b',通式是v[ch-‘a']。最后输出的时候,遍历数组并进行修改即可。这样有点像链表,保存了数组的索引。

在这个思路上继续优化,可以再开一个数组,保存26个数组的索引,交换的时候,交换索引,这样就不用交换数组里的元素了。这个代码没写,有兴趣的朋友可以自己动手试试。

#include <cstdio>
#include <iostream>
#include <string>
#include <sstream>
#include <cstring>
#include <stack>
#include <queue>
#include <algorithm>
#include <cmath>
#include <map>
#define ms(a) memset(a,0,sizeof(a))
#define msp memset(mp,0,sizeof(mp))
#define msv memset(vis,0,sizeof(vis))
using namespace std;
//#define LOCAL
int main()
{
#ifdef LOCAL
    freopen("in.txt", "r", stdin);
#endif // LOCAL
    //Start
    string s;
    vector<string::iterator> v[26];
    int m,n;
    while(cin>>m>>n)
    {
        cin>>s;
        string::iterator it;
        for(it=s.begin(); it!=s.end(); it++)
        {
            v[*it-'a'].push_back(it);
        }
        char a,b;
        while(n--)
        {
            cin>>a>>b;
            v[a-'a'].swap(v[b-'a']);
        }
        for(int i=0;i<26;i++)
        {
            while(!v[i].empty())
            {
                it=v[i].back(),v[i].pop_back();
                *it=i+'a';
            }
        }
        cout<<s<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/gpsx/p/5168683.html