Hacking SPOJ - HACKING
题意:给你一个长度为n的字符串,找出一个长度小于等于m的字符串s1,并且字符串s1的里的字母要小于'a'+k,并输出。
思路:这题刚开始完全没思路啊,随意写都一直tle,后来大佬提点说,字典树初始化太耗时间了,就用了一个变量解决了这个麻烦,并且s1的长度是小于m不是等于m,所以这里要注意。
AC代码:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
int cnt,tot,n, m, k,res;
const int maxn = 1e6+10;
char ch[maxn], s[110];
struct Node{
int num[30];
int word[30];
}node[maxn];
void add(char *s, int len){
int u = 0;
for(int i = 0; i < len; i++){
int t = s[i] - 'a';
if(t >= k) //大于等于K的就不影响结果,剪枝
return;
if(len > m)
return;
if(node[u].num[t] != cnt){
node[u].num[t] = cnt;
node[u].word[t] = ++tot;
}
u = node[u].word[t];
}
}
int dfs(int u, int len){ //暴力查询
if(len > m)
return 0;
for(int i = 0; i < k; i++){
if(node[u].num[i] != cnt){
s[res++] = i +'a';
return 1;
}
if(dfs(node[u].word[i], len+1)){
s[res++] = i +'a';
return 1;
}
}
return 0;
}
int main(){
int t;
cin>>t;
cnt = 0;
while(t--){
cnt++;
cin>>n>>m>>k;
scanf("%s",&ch);
memset(s, 0, sizeof(s));
tot = res = 0;
for(int i = 0, j; i < n; i++){
for(j = 0; j < m && ch[i+j]; j++){ //用字典树存下所有小于等于m的字符串
s[j] = ch[i+j];
}
add(s, j);
}
int ans = dfs(0, 1);
for(int i = res - 1; i >= 0; i--) //倒序输出
printf("%c",s[i]);
puts("");
}
return 0;
}