与7无关的数(前缀和)

前缀和:

一个正整数,如果它能被7整除,或者它的十进制表示法中某个位数上的数字为7,则称其为与7相关的数。求所有小于等于N的与7无关的正整数的平方和。

例如:N = 8,<= 8与7无关的数包括:1 2 3 4 5 6 8,平方和为:155。

Input

第1行:一个数T,表示后面用作输入测试的数的数量。(1 <= T <= 1000) 
第2 - T + 1行:每行1个数N。(1 <= N <= 10^6)

Output

共T行,每行一个数,对应T个测试的计算结果。

Sample Input

5
4
5
6
7
8

Sample Output

30
55
91
91
155

我们可以注意题目中的数据的范围:多组数据(不超过1000组),每组数据整数N.(1≤N≤1000000)。如果我们每一次取出一个数据都要计算与7无关的数都要进行M次运算,然后数据范围为1~1e6,所以时间复杂度为O(T*M*N);显然会超时.

于是我们运用了前缀和思想,先把数据范围内的数全部存起来,然后每次使用直接取出就行,这样时间复杂度就是O(T)+O(M*N),即O(M*N).
代码:

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <vector>
using namespace std;
const int max1=1000005;
typedef long long LL;
LL sum[max1];
int find1(LL a)
{
    int flag1=0;
    if(a%7==0)
    {
        return 0;
    }
    while(a)
    {
        if(a%10==7)
        {
            flag1=1;
            break;

        }
            a/=10;

    }
    if(flag1==1)
        return 0;
    return 1;
}
int main()
{
    LL n,i;
    LL t;
    memset(sum,0,sizeof(sum));
    for(i=1;i<=1000000;i++)
    {
        int flag;
        flag=find1(i);
        if(flag==1)
        {
            sum[i]=sum[i-1]+i*i;
        }
        else
            sum[i]=sum[i-1];
    }
    scanf("%lld",&t);
    while(t--)
    {
        scanf("%lld",&n);
        printf("%lld\n",sum[n]);
    }
    return 0;

}

前缀和的思想感觉就是预处理,采用空间换时间的方法,先把数据求出来,然后直接使用就行了.

猜你喜欢

转载自blog.csdn.net/qq_38984851/article/details/81098256