2017-08-04
The name of one small but proud corporation consists of n lowercase English letters. The Corporation has decided to try rebranding — an active marketing strategy, that includes a set of measures to change either the brand (both for the company and the goods it produces) or its components: the name, the logo, the slogan. They decided to start with the name.
For this purpose the corporation has consecutively hired m designers. Once a company hires the i-th designer, he immediately contributes to the creation of a new corporation name as follows: he takes the newest version of the name and replaces all the letters xi by yi, and all the letters yi by xi. This results in the new version. It is possible that some of these letters do no occur in the string. It may also happen that xi coincides with yi. The version of the name received after the work of the last designer becomes the new name of the corporation.
Manager Arkady has recently got a job in this company, but is already soaked in the spirit of teamwork and is very worried about the success of the rebranding. Naturally, he can‘t wait to find out what is the new name the Corporation will receive.
Satisfy Arkady‘s curiosity and tell him the final version of the name.
Input
The first line of the input contains two integers n and m (1?≤?n,?m?≤?200?000) — the length of the initial name and the number of designers hired, respectively.
The second line consists of n lowercase English letters and represents the original name of the corporation.
Next m lines contain the descriptions of the designers‘ actions: the i-th of them contains two space-separated lowercase English letters xi and yi.
Output
Print the new name of the corporation.
Example
Input
6 1policep m
Output
molice
Input
11 6abacabadabaa bb ca de gf ab b
Output
cdcbcdcfcdc 题目大意 : 经过m次的交换后,最初的字符串变成什么样了。 题目分析 : 这道题本来就是道水题,但是考试的时候没有好好分析它的时间复杂度,一直不敢写循环。那我们现在就来好好分析一下它的时间复杂度吧!如果用最笨的方法去做,也就是 每输入一次,我们遍历整个字符串,全部交换一遍。时间复杂度O(n*m),那我们去最坏的情况来计算,也就是n=m=2*105,n*m就是4*1010次,想也不用想在一秒内肯定会超时。那怎 么办呢?我们在仔细想想,每一次输入交换的字符,无非是两个字符的值互换,那我们为什么不可以直接得最后每个字符等于什么字符呢?比如说:a和b交换,我们先不在字符串里 进行交换,而是将两者直接交换,也就是a=b,b=a。再交换b,c,那么a=b=c,b=a不变,c=b。依次类推,得到a,b,c,d最终为什么值,问题不就解决了吗?那我们再来看看它 的时间复杂度吧!输入的时候判断,并循环26个字母(找到a,变成b,找到b,变成a),最后一次遍历字符串,O(26*m+n)26又可以忽略不计,所以O(m+n)。最坏情况也不过 4*105,怎么也不会超时了。 题目收获 :数组下标的利用。也正是这个问题一直让我很困扰,也是没有想到吧!
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; char s[300009]; char ch[30]; int main() { int n,m;scanf("%d%d",&n,&m); scanf("%s",s); for(int i=0;i<26;i++) ch[i]=i+‘a‘; for(int i=0;i<m;i++) { char a,b; scanf(" %c %c",&a,&b); for(int j=0;j<26;j++) { if(ch[j]==a) ch[j]=b; else if(ch[j]==b) ch[j]=a; } } for(int i=0;i<n;i++) { printf("%c",ch[s[i]-‘a‘]);//充分利用下标,a就是1,b就是2. } }