CodeForces 591B

题目链接:

http://codeforces.com/problemset/problem/591/B

题意:

给你一串字符串,字符串里的字符全是a-z的小写字母,下面的m行,是字符串的交换方式, 如果输入的是 x  y,则是字母x与字母y交换,且字母y与字母x也要交换

解题思路:

n和m的范围在2*10^5内,如果直接暴力肯定会超时;

所以只能采取智慧的方法

可以先定义

char a[26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',};

将26个小写字母全都放在数组中存好

然后每输入一行交换方式,即对字符串中相关的字母进行变换

for(j=0;j<26;j++)
{
if(a[j]==b[0]) {a[j]=b[1];continue;}//x=j;//{x=j; cout<<"x="<<x<<endl;}
if(a[j]==b[1]) a[j]=b[0]; //y=j;//{y=j;cout<<",y="<<y<<endl;}
}

全部都交换完后,现在字符串a中的字符即是交换后的值,

for(i=0;i<n;i++)
printf("%c",a[str[i]-97]);

程序代码:

#include <cstdio>
#include <iostream>
using namespace std;
const int M=200000+10;
int main()
{
int m,n,i,j;
char a[26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',};
char str[M],b[2];
cin>>n>>m>>str;
while(m--)
{ int x,y;
  cin>>b[0]>>b[1];
  //cout<<b[0]<<b[1];
  for(j=0;j<26;j++)
  {
   if(a[j]==b[0])       {a[j]=b[1];continue;}//x=j;//{x=j; cout<<"x="<<x<<endl;}
   if(a[j]==b[1])  a[j]=b[0]; //y=j;//{y=j;cout<<",y="<<y<<endl;}
  }
  //a[x]=b[1];//cout<<"x="<<x<<" a[x]="<<a[x]<<endl;
  //a[y]=b[0];//cout<<"y="<<y<<" a[y]="<<a[y]<<endl;
}
for(i=0;i<n;i++)
 printf("%c",a[str[i]-97]);
printf("
");
return 0;
}
View Code
原文地址:https://www.cnblogs.com/www-cnxcy-com/p/5539771.html