Problem Description
Carryon最近喜欢上了一些奇奇怪怪的字符,字符都是英文小写字母,但奇怪的是a可能比b小,也可能比b大,好奇怪。与此同时,他拿到了好多的字符串,可是看着很不顺眼,因为他们很乱,所以他想将这些字符串按字典序从小到大排下序,这样就好看多了。由于a可能比b小,也可能比b大,这样按常规方法肯定是不行的,幸运的是他破解了26个字母的大小顺序,这样他就开开心心的将字符串从小到大排序了。
Input
第一行输入26个字符的大小顺序
第二行输入一个n(1≤n≤105)。
接下来n行,每行一个字符串si,数据保证每个字符串不重复。(1≤∑i = 1nlen(si)≤3×105)
Output
将n个字符串按字典序从小到大输出。
Sample Input
abcdefghijklmnopqrstuvwxyz
5
bcda
licj
lin
aaaa
aaaaa
Sample Output
aaaa
aaaaa
bcda
licj
lin
#include<iostream>
#include<string.h>
#include<algorithm>
#include<map>
#define maxn 1111111
using namespace std;
int pos = 1;
char s[26], str[maxn];
int t[maxn][26];
bool vis[maxn];
map<char, int>mm;
void insert(char *s)
{
int rt = 0, len = strlen(s);
for (int i = 0; i<len; i++)
{
int x = mm[s[i]];
if (!t[rt][x])//如果没有从rt到x的字符串前缀,插入一个
t[rt][x] = pos++;//按查询字符串的每个字符输入顺序进行标记
rt = t[rt][x];//为下一次标记准备,将当前节点作为下一次标记的上一个节点
}
vis[rt] = 1;//在每次输入的一个字符串的最后一个字符标记
}
void dfs(int rt, int deep)
{
for (int i = 0; i<26; i++)//从第一个字符开始找(第一个字符就是最小的)
{
if (t[rt][i])//如果有从rt到i的字符串前缀
{
str[deep] = s[i];//str[]记录s[i]字符串
if (vis[t[rt][i]])//搜到s[]串的最后一个字符就输出这个字符串
{
str[deep + 1] = '\0';//'\0'字符串结束符,字符串的结束标志
printf("%s\n", str);
}
dfs(t[rt][i], deep + 1);
}
}
return;
}
int main()
{
scanf("%s", s);
for (int i = 0; i<26; i++)
mm[s[i]] = i;
int n;
scanf("%d", &n);
memset(vis, 0, sizeof(vis));
for (int i = 0; i<n; i++)
{
char ss[3333333];
scanf("%s", ss);
insert(ss);
}
dfs(0, 0);
return 0;
}
#include<iostream>
#include<cstring>
#include<algorithm>
#include<string>
#include<map>
#define N 100005
using namespace std;
map<char, char>m;
struct node
{
string s;//s是输入的字符串
string ss;//ss是映射之后的字符串
}str[N];
bool cmp(node a, node b)
{
return a.ss<b.ss;
}
int main()
{
char New[100];
scanf("%s", New);
for (int i = 0; i<26; i++)
{
m[New[i]] = 'a' + i;//构建映射
}
int n;
scanf("%d", &n);
for (int i = 0; i<n; i++)
{
cin >> str[i].s;
int len = str[i].s.length();
for (int j = 0; j<len; j++)
{
str[i].ss += m[str[i].s[j]];//使用上面的映射关系
}
}
sort(str, str + n, cmp);
for (int i = 0; i<n; i++)
{
cout << str[i].s << endl;
}
return 0;
}