算法入门(3)

本文介绍了几个算法练习题目,包括得分问题、分子量计算、数数字统计、组合数计算、素数判断、刽子手游戏判断及人数出列问题,通过实例解析并提供了解题思路,适合算法初学者提升技能。
摘要由CSDN通过智能技术生成

在上一篇博客基础,我又写了一些算法小程序,同样这些程序来自《算法竞赛入门经典》这本书,强烈推荐这本书,对学习算法帮助很大。

  1. 得分问题
    问题描述:给出一个由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;
                     }
                     
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值