2020牛客寒假算法基础集训营5:H——Hash

链接:https://ac.nowcoder.com/acm/contest/3006/H
来源:牛客网

题目描述
这里有一个hash函数
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;
}
现给定一个长度为66的仅由小写字母构成的字符串ss和模数modmod,请找到字典序最小且大于ss的一个长度为66的仅由小写字母构成的字符串s’s

,使得其hash值和ss的hash相等。

输入描述:
多组用例,请处理到文件结束。(用例组数大约为1000组左右)

对于每组用例,输入一行,包含一个长度为66的仅由小写字母构成的字符串ss和模数mod(2 \leq mod \leq 10^7)mod(2≤mod≤10
7
),用空格隔开。

输出描述:
对于每组用例,如果存在如题目所述的s’s

,请输出s’s

,否则输出-1。
示例1
输入
复制
abcdef 11
输出
复制
abcdeq

思路:

首先要想hash不变,可以在原来的hash加上mod,那么取模后就会不变了;所以就得到一个新的字符串的hash值为;原来的hash+mod;
首先
观察给的哈希函数可以轻松(狗屁)看出,这个哈希函数就仅仅是把一个只由小写字符组成的字符串当成了一个26进制的数,不取模的情况下,任意小写字符串和自然数是一一对应的。因此,只要把给的字符串转换成对应的26进制整数,加上模数后转换回字符串,一定可以得到一个最小字典序大于原串的字符串。只要这个新字符串长度为6即是满足要求的字符串。
(把循环展开就可以看出来他是个26进制转化十进制的过程)
在这里插入图片描述

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
char str[7];
int main()
{
	string s;
	int mod;
	while(cin>>s>>mod)
	{
		ll res=0,cot=0;
		for(int i=0;i<s.size();i++)
		{
			res=res*26+s[i]-'a';
		}
		res+=mod;
		for(int i=s.size()-1;i>=0;i--)
		{
			str[i] = res % 26 + 'a';
            res /= 26;
		}
		if(res) puts("-1");
		else cout <<str<<endl;
	}
}
发布了197 篇原创文章 · 获赞 36 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43872728/article/details/104310296
今日推荐