2020牛客寒假算法基础集训营5.H——Hash【思维 & 哈希 & 进制】

题目传送门


题目描述

这里有一个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;
}

现给定一个长度为6的仅由小写字母构成的字符串s和模数modmod,请找到字典序最小且大于s的一个长度为6的仅由小写字母构成的字符串s’ ,使得其hash值和s的hash相等。


输入描述:

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

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


输出描述:

对于每组用例,如果存在如题目所述的s’ ,请输出s′ ,否则输出-1。


输入

abcdef 11


输出

abcdeq


题解

  • 观察给的哈希函数可以轻松看出,这个哈希函数就仅仅是把一个只由小写字符组成的字符串当成了一个26进制的数。
  • 不取模的情况下,任意小写字符串和自然数是一一对应的。
  • 因此,只要把给的字符串转换成对应的26进制整数,加上模数后转换回字符串,一定可以得到一个最小字典序大于原串的字符串。
  • 只要这个新字符串长度为6即是满足要求的字符串。

AC-Code

#include <bits/stdc++.h>
using namespace std;

int main() {
	string s; int mod;	while (cin >> s >> mod) {
		int res = 0;
		for (int i = 0; i < s.length(); ++i) 
			res = res * 26 + s[i] - 'a';
		res += mod;
		for (int i = s.length() - 1; i >= 0; --i) {
			s[i] = res % 26 + 'a';
			res /= 26;
		}
		if (res)	puts("-1");
		else	puts(s.c_str());
	}
}
发布了181 篇原创文章 · 获赞 112 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Q_1849805767/article/details/104301422