Time limit:1 Sec Memory limit:128 MB
Description
There is a string of n length (containing only lowercase letters), the operation M times, each operation exchanges two letters, the output of the final string.
Input
Multiple sets of inputs, with each set of first behavior n,m representing string lengths and operands, 1<n,m<=100000
The second behavior is a string of length n, followed by M-line, two characters per line, separated by the middle space, representing the two characters to be exchanged.
Output
Each set of data outputs a row representing the final string.
Sample Input5 1Lehhoh L6Abacabadabaa Bb Ca De Gf ab bSample OutputHelloCDCBCDCFCDCHINT
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
Solution: If the general method, that is, the real exchange, the data given 100000 of the string will be tle, then think of the array to save the index of each letter, so do not have to enter two characters each time to cycle. However, even so, the idea at first is to swap the contents of two arrays and modify the string so that the string is actually modified, so it times out. Later found that there is no need to change the contents of the string every time, as long as the output when the change is good.
So, the idea is: Use 26 arrays, first loop through the string, save 26 letters of the index (because of a string, so save an iterator), and then, every read two letters, swap (using the SWAP function) two arrays, here v[0] is ' a ', v[1] is ' B ' , the general formula is v[ch-' a ']. At the end of the output, iterate through the array and modify it. This is a bit like a linked list, which holds the index of the array.
Continue to optimize in this way, you can open an array, save the index of 26 arrays, swap, swap the index, so that you do not have to swap the elements in the array. This code is not written, interested friends can try their own hands.
#include <cstdio>#include<iostream>#include<string>#include<sstream>#include<cstring>#include<stack>#include<queue>#include<algorithm>#include<cmath>#include<map>#defineMS (a) memset (A,0,sizeof (a))#defineMSP Memset (Mp,0,sizeof (MP))#defineMSV memset (vis,0,sizeof (VIS))using namespacestd;//#define LOCALintMain () {#ifdef LOCAL freopen ("In.txt","R", stdin);#endif //LOCAL //Start strings; Vector<string::iterator> v[ -]; intM,n; while(cin>>m>>N) {cin>>s; string:: Iterator it; for(It=s.begin (); It!=s.end (); it++) {v[*it-'a'].push_back (IT); } Charb; while(n--) {cin>>a>>b; V[a-'a'].swap (v[b-'a']); } for(intI=0;i< -; i++) { while(!V[i].empty ()) {It=v[i].back (), V[i].pop_back (); *it=i+'a'; }} cout<<s<<Endl; } return 0;}
Zufe (Zhou Sai) 2326 Exchange Letter (STL)