It is a well-known fact that behind every good comet is a UFO. These UFOs often come to collect loyal supporters from here on Earth. Unfortunately, they only have room to pick up one group of followers on each trip. They do, however, let the groups know ahead of time which will be picked up for each comet by a clever scheme: they pick a name for the comet which, along with the name of the group, can be used to determine if it is a particular group's turn to go (who do you think names the comets?). The details of the matching scheme are given below; your job is to write a program which takes the names of a group and a comet and then determines whether the group should go with the UFO behind that comet.
Both the name of the group and the name of the comet are converted into a number in the following manner: the final number is just the product of all the letters in the name, where "A" is 1 and "Z" is 26. For instance, the group "USACO" would be 21 * 19 * 1 * 3 * 15 = 17955. If the group's number mod 47 is the same as the comet's number mod 47, then you need to tell the group to get ready! (Remember that "a mod b" is the remainder left over after dividing a by b; 34 mod 10 is 4.)
首先给出我当时通过的代码
/* ID: fuchenc1 PROG: ride LANG: C++ */ #include <fstream> #include <string> #include <iostream> using namespace std; int CalculateName(const string& strName) { int len=strName.length(),res=1; for(int i=0;i<len;i++) { res*=((char)strName[i]-'A'+1); } return res; } int main() { ifstream fin("ride.in"); ofstream fout("ride.out"); string strGroupName,strComtName,answer="STAY"; fin>>strGroupName>>strComtName; if((CalculateName(strGroupName)%47)==(CalculateName(strComtName)%47)) { answer="GO"; } fout<<answer<<endl; return 0; }
接下来是我通过测试后,题目给出的参考答案:
#include <stdio.h> #include <ctype.h> int hash(char *s) { int i, h; h = 1; for(i=0; s[i] && isalpha(s[i]); i++) h = ((s[i]-'A'+1)*h) % 47; return h; } void main(void) { FILE *in, *out; char comet[100], group[100]; /* bigger than necessary, room for newline */ in = fopen("input.txt", "r"); out = fopen("output.txt", "w"); fgets(comet, sizeof comet, in); fgets(group, sizeof group, in); if(hash(comet) == hash(group)) fprintf(out, "GO\n"); else fprintf(out, "STAY\n"); exit (0); }
参考答案当中有一个亮点,就是这行代码:
h = ((s[i]-'A'+1)*h) % 47;
利用这个方法有个非常大的好处,不容易产生数据溢出,因为如果是将各个字母的数直接相乘之后,再对总结果求余,在字母非常多的时候,有可能求出来的积早就超过了整型所能表示的最大范围了,而采用参考答案给出的方法,就不会产生这种问题。当然这道题最多只有6个字母,因此也不会产生这个问题。
所以通过这道题应该学习到求余的这个小技巧: (A*B)%C=(A*(B%C))%C。