把名字中字母编号连乘并始终对 47 取模,比较彗星名和团队名的余数。
OJ: luogu
题目 ID: P1200
难度:入门
标签:字符串模拟数学python
日期: 2026-07-15 21:01
题意
给定彗星名和团队名。把每个字母转成 A=1, B=2, ..., Z=26,分别计算所有字母编号的乘积。如果两个乘积对 47 的余数相同,输出 GO,否则输出 STAY。
思路
写一个函数 name_value(name),扫描名字中的每个大写字母:
text
编号 = ord(ch) - ord("A") + 1乘积可能变大,但只关心模 47 的结果,所以每乘一次就取模:
python
result = result * 编号 % 47最后比较两个名字的结果即可。
这题是字符编号和取模练习,不创建 brute.py。
Python 知识
/home/rainboy/mycode/hugo-blog/content/program_language/python/input_output_and_strings.md:用input().strip()读取不含空格的字符串。/home/rainboy/mycode/hugo-blog/content/program_language/python/math_tools.md:取模可以控制中间数大小,并保留余数信息。ord(ch)可以得到字符编码,适合把大写字母转成1..26。
代码
python
def name_value(name):
result = 1
for ch in name:
result = result * (ord(ch) - ord("A") + 1) % 47
return result
comet = input().strip()
group = input().strip()
if name_value(comet) == name_value(group):
print("GO")
else:
print("STAY")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-07-27 00:00
* update_at: 2026-07-27 00:00
*/
#include <bits/stdc++.h>
using namespace std;
char comet[10], group[10]; // 彗星名和团队名
// 计算名字的模 47 值:字母编号乘积 % 47
int name_value(char *name) {
int res = 1;
int len = strlen(name);
for (int i = 0; i < len; i++) {
int num = name[i] - 'A' + 1; // A=1, B=2, ...
res = res * num % 47;
}
return res;
}
int main() {
cin >> comet >> group;
if (name_value(comet) == name_value(group))
cout << "GO";
else
cout << "STAY";
return 0;
}Pythonic 写法
functools.reduce 计算名字乘积模 47:
python
from functools import reduce
def name_value(name: str) -> int:
return reduce(lambda value, ch: value * (ord(ch) - 64) % 47, name, 1)
print("GO" if name_value(input().strip()) == name_value(input().strip()) else "STAY")复杂度
名字长度最多为 6,时间复杂度和空间复杂度都可视为
总结
字母编号题常用 ord(ch) - ord("A") + 1。只比较余数时,可以在连乘过程中持续取模。