一般我们在对字符串排序时,都会按照字典序排序。当字符串只包含小写字母时,相当于按字母表"abcdefghijklmnopqrstuvwxyz"的顺序排序。
现在我们打乱字母表的顺序,得到一个26个字母的新顺序。例如"bdceafghijklmnopqrstuvwxyz"代表'b'排在'd'前,'d'在'c'前,'c'在'e'前……
给定N个字符串,请你按照新的字母顺序对它们排序。
Input第一行包含一个整数N。(1 <= N <= 1000)
第二行包含26个字母,代表新的顺序。
以下N行每行一个字符串S。 (|S| <= 100)
Output按新的顺序输出N个字符串,每个字符串一行。
5 bdceafghijklmnopqrstuvwxyz abcde adc cda cad ddcSample Output
ddc cda cad abcde adc
题意就不多说了,就是重新定义了一下字典序,然后给你几串字符串,要求你按新的字典序,从小到大输出这些字符串。
解:按照给出的新的字典序的顺序,把要排序的字符串的中的所有出现的新字典序中的第一个字母换成a(因为cmp函数里用string比较字符串大小,而string默认a最小,z最大 ,所以将所给字典序26个字母等价转换成a-z),相应的新字典序中出现的第二个字母换成b,以此类推……最后再把字符串sort一下(需要写一个cmp函数)输出就行了。首先开一个map存题目给出的字典序,然后再开一个结构体来操作要排序的字符串。详细看代码注释。
ps:比赛时写的代码超时了,当时感觉很纳闷,10s的时间怎么可能会超时?刚才点开比赛时提交的代码,发现原来是数组开小了(应该是写了其他的题忘记改数组的大小),,,,,,
赛后代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<iostream>
#include<algorithm>
#include<queue>
#include<map>
#include<vector>
using namespace std;
typedef long long LL;
const int N=1e3+1;
char ss[30];//s存新的字典序
map<char,int>mapp;//map记录下标
struct node
{
string a,b;//a存要排序的字符串
}s[N];
bool cmp(node x,node y)//自定义字符串比较函数
{
return x.b<y.b;
}
int main()
{
int n;
scanf("%d%s",&n,ss);
for(int i=0;ss[i]!='\0';i++)
mapp[ss[i]]=i;
for(int i=0;i<n;i++)
{
cin>>s[i].a;
s[i].b=s[i].a;//将a附给b,然后把b字符串转换成新的字典序的值
for(int j=0;s[i].b[j]!='\0';j++)
s[i].b[j]=mapp[s[i].b[j]]+'a';
}
sort(s,s+n,cmp);//最后将b字符串sort一下输出结果就行了
for(int i=0;i<n;i++)
cout<<s[i].a<<endl;
}
比赛时的代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
#include<math.h>
#include<iostream>
#include<queue>
#include<set>
#include<map>
#include<stack>
#include<vector>
using namespace std;
typedef long long LL;
const int N=1e3+1;
char ss[30];
bool vis[30];
struct node
{
char a[N];
char b[N];
}s[N];
bool cmp(node x,node y)
{
return strcmp(x.b,y.b)<0;
}
int main()
{
int n;
scanf("%d",&n);
scanf("%s",ss);
for(int i=0;i<n;i++)
{
scanf("%s",s[i].a);
int t=0;
for(int j=0;s[i].a[j]!='\0';j++)
{
for(int k=0;ss[k]!='\0';k++)
{
if(s[i].a[j]==ss[k])
{
s[i].b[t++]=k+'0';
break;
}
}
}
}
sort(s,s+n,cmp);
for(int i=0;i<n;i++)
{
for(int j=0;s[i].b[j]!='\0';j++)
{
printf("%c",ss[s[i].b[j]-'0']);
}
printf("\n");
}
}