Regionals 2014 >> Latin America >> 6823 - Counting substhreengs

6823 - Counting substhreengs

题目:

Regionals 2014 >> Latin America >> 6823 - Counting substhreengs_第1张图片

题目大意:1.子串只包含连续数字 2.该数字为3的倍数 。问这种子串存在多少个?

题目思路:直接暴力会超时,优化为n的复杂度。遍历该字符串,如果该位是数字,求出其与3的余数,填入表格。

题目链接:6823 - Counting substhreengs

以下是代码:

#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <string>
#include <cstring>
using namespace std;

int main(){
    string s;
    while(cin >> s)
    {
        long long t1 = 0,t2 = 0,t3 = 0;
        long long ans = 0;
        for (int i = 0; i < s.size(); i++)
        {
            if (isdigit(s[i]))
            {
                int num = (s[i] - '0') % 3;
                long long ret1,ret2,ret3;  //记录新表格值
                if (num == 0)   //余数为0时,新表格值内余数为0的加1;
                {
                    ret1 = t1 + 1,ret2 = t2,ret3 = t3;
                }
                else if (num == 1)//余数为1时,余数为0的值→由原来余数为2的值得到;以此类推。另外余数为1的值需加1
                {
                    ret1 = t3,ret2 = t1 + 1,ret3 = t2;   
                }
                else //余数为2时,余数为0的值→由原来余数为1的值得到;以此类推。另外余数为2的值需加1
                {
                    ret1 = t2,ret2 = t3,ret3 = t1 + 1;
                }
                ans += ret1;  //余数为0的个数就是所求答案
                t1 = ret1,t2 = ret2,t3 = ret3; //更新表格内值
            }
            else
            {
                t1 = 0,t2 = 0,t3 = 0;
            }
        }
        cout << ans << endl;
    }
    return 0;
}

你可能感兴趣的:(Regionals,6823)