将名字中的字母映射为 1 到 26 的数值并累乘模 47,判断两个名字所得模数是否相等。
OJ: roj
题目 ID: 2000
难度:入门
标签:模拟字符串
创建: 2026-10-01 02:03
更新: 2026-10-06 02:04
题目描述
每个人都有两个名字。名字中每个大写字母对应 1~26 的数值(A=1,Z=26),名字的最终数字是所有字母对应数值的乘积 mod 47。若两个名字的数值相等则输出 GO,否则输出 STAY。名字长度 1~6。
思路
遍历每个字符,将其转为对应数值后累乘并对 47 取模,分别计算两个名字的结果再比较即可。
参考代码
Python 版:
python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-05-22 19:17
# update_at: 2026-05-22 19:17
import sys
from functools import reduce
from operator import mul
MOD = 47
def name_score(name: str) -> int:
"""计算名字所有字母对应数值(A=1..Z=26)的乘积模 47 的值。"""
return reduce(mul, (ord(ch) - ord('A') + 1 for ch in name), 1) % MOD
def solve() -> None:
data = iter(sys.stdin.buffer.read().split())
first_name = next(data, b"").decode()
if not first_name:
return
second_name = next(data).decode()
is_matched = name_score(first_name) == name_score(second_name)
print("GO" if is_matched else "STAY")
if __name__ == "__main__":
solve()C++ 版(同一算法):
cpp
/**
* Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
* rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
* rainboy的学习导航网站: https://idx.roj.ac.cn
* create_at: 2026-10-06 02:04
* update_at: 2026-10-06 02:04
*/
#include <iostream>
#include <string>
using namespace std;
typedef long long ll;
const ll MOD = 47;
// 计算名字所有字母对应数值(A=1..Z=26)的乘积模 47
ll name_score(const string &s) {
ll res = 1;
for (ll i = 0; i < (ll)s.size(); ++i) {
res = (res * (s[i] - 'A' + 1)) % MOD;
}
return res;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string s1, s2;
cin >> s1 >> s2;
if (name_score(s1) == name_score(s2))
cout << "GO\n";
else
cout << "STAY\n";
return 0;
}