在上一篇博客基础,我又写了一些算法小程序,同样这些程序来自《算法竞赛入门经典》这本书,强烈推荐这本书,对学习算法帮助很大。
- 得分问题
问题描述:给出一个由O和X组成的串(长度为1~80),统计得分。每个O的得分为目前连续出现 的O的个数,X的得分为0。例如,OOXXOXXOOO的得分为1+2+0+0+1+0+0+1+2+3。
#include<stdio.h>
#include<iostream>
#include <string.h>
using namespace std;
#define maxn 1000
int main(){
char s[maxn];
int n;
scanf("%d", &n);
while (n--)
{
scanf("%s", s);
int mark = 0;
int score = 0;
for (int i = 0; i < strlen(s); i++)
{
if (s[i]=='O') //遍历输入字符串,当为O时
{
mark++; //增加标记
score += mark;
}
else
{
mark = 0;
score += mark;
}
}
printf("score:%d", score);
}
system("pause");
return 0;
}
2、分子量问题
问题描述:给出一种物质的分子式(不带括号),求分子量。本题中的分子式只包含4种原子,分 别为C, H, O, N,原子量分别为12.01, 1.008, 16.00, 14.01(单位:g/mol)。例如,C6H5OH的 分子量为94.108g/mol。
#include<stdio.h>
#include<iostream>
#include <string.h>
#include <ctype.h>
using namespace std;
#define maxn 1000
int main(){
char s[maxn];
int n;
scanf("%d", &n);
while (n--)
{
scanf("%s", s);
double num = 0.0;
for (int i = 0; i < strlen(s); i++)
{
if (s[i]=='C')
{
if (isdigit(s[i+1]))
{
int m = s[i + 1] - '0';
num += 12.01*m;
}