Codeforces 385C Bear and Prime Numbers (prime preprocessing)


Codeforces 385C Bear and Prime Numbers
is actually not a problem worth recording. By quickly typing the prime number table and preprocessing the prefix sum, the complexity of the query becomes O(1).
However, I used map to count the number of elements in the array, so that when I do the accumulation of prefix and sum, I have to query the map every time, even TLE. But I never found out, thinking that Euler sieve was not good enough for this problem, so I searched the Internet to solve the problem, and found that others did almost the same way, but they were able to run through it. After struggling for a long time, I remembered that it was the reason for the map. The internal implementation of map is a red-black tree, and the complexity of each query is O(logN) , which leads to timeout when the time is not rich. After switching to an array for statistics, the AC goes smoothly. When doing a question, if space allows, try to use an array to do the mapping between integers, because this question has been tangled for a long time, so make a record.
Attach the AC code:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<vector>
#include<queue>
#include<map>
#include<cmath>
#include<algorithm>
#include<climits>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
typedef map<int, int> M;
typedef vector<int> V;
typedef queue<int> Q;
const int maxn=10000000+5;
int cnt[maxn];
bool is[maxn];
int prime[maxn/2];
ll sum[maxn];
void init(int mx)
{
    int i,j,count=0;
    for (i=2;i<=mx;++i)
    {
        if (!is[i])
        {
            prime[count++]=i;
        }
        for (j=0;j<count&&i*prime[j]<=mx;++j)
        {
            is[i*prime[j]]=true;
            if (i%prime[j]==0)
                break;
        }       
    }
    for (i=2;i<=mx;++i)
    {
        if (!is[i])
        {
            for (j=1;j*i<=mx;++j)
            {
                sum[i]+=cnt[i*j];
            }
            sum[i]+=sum[i-1];
        }
        else
            sum[i]=sum[i-1];
    }
    return;
}
int main()
{
    int n,t,m,k,i,j;
    cin>>n;
    for (i=0;i<n;++i)
    {
        scanf("%d",&t);
        cnt[t]++;
    }   
    init(maxn); 
    cin>>m;
    while (m--)
    {
        int l,r;
        scanf("%d%d",&l,&r);
        l=min(maxn,l);
        r=min(maxn,r);
        printf("%d\n",sum[r]-sum[l-1]);     
    }
    return 0;
} 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325118167&siteId=291194637