- POJ 3094 - Quicksum
- Time: 1000MS
- Memory: 10000K
- 难度: 水题
- 分类: 无
0x00 POJ 原题
Description
A checksum is an algorithm that scans a packet of data and returns a single number. The idea is that if the packet is changed, the checksum will also change, so checksums are often used for detecting transmission errors, validating document contents, and in many other situations where it is necessary to detect undesirable changes in data.
For this problem, you will implement a checksum algorithm called Quicksum. A Quicksum packet allows only uppercase letters and spaces. It always begins and ends with an uppercase letter. Otherwise, spaces and letters can occur in any combination, including consecutive spaces.
A Quicksum is the sum of the products of each character’s position in the packet times the character’s value. A space has a value of zero, while letters have a value equal to their position in the alphabet. So, A=1, B=2, etc., through Z=26. Here are example Quicksum calculations for the packets “ACM“ and “MID CENTRAL“:
ACM: 1*1 + 2*3 + 3*13 = 46
MID CENTRAL: 1*13 + 2*9 + 3*4 + 4*0 + 5*3 + 6*5 + 7*14 + 8*20 + 9*18 + 10*1 + 11*12 = 650
Input
The input consists of one or more packets followed by a line containing only # that signals the end of the input. Each packet is on a line by itself, does not begin or end with a space, and contains from 1 to 255 characters.
Output
For each packet, output its Quicksum on a separate line in the output.
Sample Input
ACM
MID CENTRAL
REGIONAL PROGRAMMING CONTEST
ACN
A C M
ABC
BBC
#
Sample Output
46
650
4690
49
75
14
15
Source
0x10 解题思路
见代码注释。
0x20 AC 源码
/*
Author: Exp
Date: 2017-12-01
Code: POJ 3094
Problem: Quicksum
URL: http://poj.org/problem?id=3094
*/
/*
题意分析:
计算只含[大写字母+空格]的字符串的校验和.
其中每个字母有其对应的特征值,空格=0,A=1,B=2,...,Z=26
校验和 = 所有 [字符的位置(从1开始) * 字母特征值] 之和
*/
#include <memory.h>
#include <iostream>
using namespace std;
// 被校验字符串的最大长度
const static int MAX_LEN = 255;
/*
* 获取字符的特征值
* @param c 字符
* return 特征值
*/
int getFeatureVal(char c);
int main(void) {
char str[MAX_LEN] = { '\0' };
while(true) {
gets(str); // 输入字符串中包含空格,不能用cin接收
int len = strlen(str);
if(strlen(str) <= 0 || str[0] == '#') {
break;
}
int quicksum = 0;
for(int i = 0; i < len; i++) {
quicksum += ((i + 1) * getFeatureVal(str[i]));
}
cout << quicksum << endl;
memset(str, '\0', sizeof(char) * len);
}
return 0;
}
int getFeatureVal(char c) {
return (c == ' ' ? 0 : (c - 'A' + 1));
}