题目链接:点击查看
题目大意:给出一个长度为 6 的字符串 s ,再给出模数 mod,现在规定哈希值为如下运算:
const int LEN = 6;
int mod;
int Hash(char str[])
{
int res = 0;
for (int i = 0; i < LEN; i++)
{
res = (res * 26 + str[i] - 'a') % mod;
}
return res;
}
问是否存在一个字符串,字典序大于 s 且哈希值相等
题目分析:读完题后陷入思维定式好一段时间,固然以为哈希值是需要有字符串才行,于是想到用dfs暴力枚举子串然后全排列,一开始没计算好时间复杂度,以为是可行的,捣鼓了半天dfs,最后认真算了一遍枚举的复杂度为 26^6*A(6)*6,其中26^6是枚举字符串所需要花费的时间,A(6)是对长度为 6 的字符串全排列所需要的时间,也就是 720 ,还有常数 6 是需要计算字符串的哈希值,先不管别的,26^6就已经3e8了,显然暴力是不可行的
于是就敞开思维开始乱猜了,发现如果想要找到满足题目要求的字符串,只需将当前字符串向后 mod 个单位就好了,稍微一转换,会发现其实每一位字符代表的区间分别为[ 0 , 26 ),[ 26 , 26^2 ),[ 26^2 , 26^3 ) 以此类推,进一步再转换一下,会发现这其实不就是将字符串 s 当成一个 26 进制的数字来计算,到此为止豁然开朗,直接模拟即可
代码:
#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<unordered_map>
using namespace std;
typedef long long LL;
typedef unsigned long long ull;
const int inf=0x3f3f3f3f;
const int N=1e5+100;
int q_pow(int a,int b)
{
int ans=1;
while(b)
{
if(b&1)
ans*=a;
a*=a;
b>>=1;
}
return ans;
}
int main()
{
//#ifndef ONLINE_JUDGE
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
//#endif
// ios::sync_with_stdio(false);
string s;
int mod;
while(cin>>s>>mod)
{
int num=0;
reverse(s.begin(),s.end());
for(int i=0;i<s.size();i++)//构造26进制
num+=q_pow(26,i)*(s[i]-'a');
num+=mod;
if(num>=q_pow(26,6))
{
printf("-1\n");
continue;
}
string ans;
for(int i=0;i<6;i++)
{
ans+=(char)(num%26+'a');
num/=26;
}
reverse(ans.begin(),ans.end());
cout<<ans<<endl;
}
return 0;
}