UVa 1585 Score / 1586 Molar Mass(遍历+计数)
来源:互联网 发布:讯龙数据恢复验证码 编辑:程序博客网 时间:2024/06/03 12:31
UVa 1585 Score
原题地址
https://vjudge.net/problem/UVA-1585
题意:给定由O和X组成的串,统计得分。每个O的得分为目前连续出现的O的个数,X得分为0,如OOXXOXXOOO=1+2+0+0+1+0+0+1+2+3=10。
解题思路
本题是《算法竞赛入门经典》的习题3-1,大水题。
遍历输入字符串,用seq记录目前连续出现的O的个数,seq=0代表没有遇到O。遇到O则按照规则累加,遇到新的X则重置seq。
AC代码
#include <stdio.h>#include <stdlib.h>#include <string.h>using namespace std;int main(){ int kase; char str[100]; scanf("%d", &kase); while(kase--) { scanf("%s", str); int seq = 0, sum = 0; for (int i = 0; i<strlen(str); ++i) { if (str[i] == 'O') { sum += seq+1; //每次加之前的连续O个数和自己 seq++; //更新连续O数 } else if (str[i] == 'X' && seq) //刚遇到X seq = 0; } printf("%d\n", sum); } return 0;}
UVa 1586 Molar Mass
原题地址
https://vjudge.net/problem/UVA-1586
题意:求只含C/H/O/N四种元素的分子的摩尔质量。
解题思路
本题是《算法竞赛入门经典》的习题3-2,大水题。
遍历字符串,分为以下几种情况:
- 遍历到元素,用pre字符记录这个元素,同时记这个元素出现次数preCount为1(因为有可能后缀数字不出现)。
- 遍历到数字,取出这整个数字,记录到preCount里。
- 每次遍历到新的字母都将前一个元素的分子量累加到sum里。可以与1合并。
- 最后记得累加最后一个元素的分子量。
AC代码
#include <stdio.h>#include <string.h>#include <cctype>#include <map>using namespace std;int main(){ map<char, double> chem; chem['C'] = 12.01; chem['H'] = 1.008; chem['O'] = 16.00; chem['N'] = 14.01; chem['#'] = 0.00; int T; char str[100]; scanf("%d", &T); while(T--) { scanf("%s", str); double sum = 0; int i = 0, preCount = 0; char pre = '#'; //起始符 while (i < strlen(str)) { if (isalpha(str[i])) //遇到新的字母 { if(pre != '#') //将之前的摩尔质量累加 sum += chem[pre] * preCount; pre = str[i]; //记录该字母 preCount = 1; //该字母出现至少一次 } if (isdigit(str[i])) //遇到字母后的数字 { //取出这个数字 preCount = str[i] - '0'; while (isdigit(str[i+1])) { preCount *= 10; preCount += str[++i]-'0'; } } ++i; } sum += chem[pre] * preCount; printf("%.3f\n", sum); } return 0;}
0 0
- UVa 1585 Score / 1586 Molar Mass(遍历+计数)
- (uva)1586Molar mass
- uva 1586 - Molar mass
- UVa 1586 - Molar mass
- UVa 1586 - Molar mass
- UVA 1586 ----Molar mass
- UVA 1586 - Molar mass
- UVa 1586 Molar mass
- UVa 1586 - Molar Mass
- UVA - 1586 Molar mass
- uva 1586 - Molar mass
- UVA 1586 Molar mass
- UVa 1586 - Molar mass
- UVa-1586Molar mass
- 【Uva 1586】 Molar mass
- UVA - 1586 Molar mass
- uva 1586 - Molar mass
- Uva - 1586 - Molar mass
- spark的生态圈
- Android JNI开发入门教程
- iframe跨域调用问题
- 第六天2017/04/11(1:结构体链表基础和相关经典操作)
- 网络流-最大流
- UVa 1585 Score / 1586 Molar Mass(遍历+计数)
- Codeforces 796C 想法
- sql注入与statement和preraredstatement关联
- BZOJ4380: [POI2015]Myjnie
- URAL1991-The battle near the swamp
- magin重叠
- Windows socket编程
- hjr-SQL-SQL 常用查询语句
- hdu1516 字符串编辑距离dp