POJ2352 solution to a problem (Fenwick tree)

POJ2352 solution to a problem (Fenwick tree)

2019-12-29

Powered by Gauss

1. Topic Portal: POJ2352

2. subject to the effect:

This is a very classic template title tree array.

Subject to the effect that, given N stars, each star has a two-dimensional coordinates, the required number of stars is located in the lower left of each of stars.

3. Algorithms ideas:

This question is given immediately after the thought of Violence Act, let's calculate:

According to the title, N <= 15000, Violence Act requires double loop, that is, of 15,000 2 = 225,000,000, exceeding the second, it had to seek better and faster algorithms thinking.

When we request inquiries sum, you should think of using Fenwick tree.

At the same time, This question is the subject of the conditions we have the conditions for the use of an array of tree: Star Y coordinates listed in ascending order, equal to the Y coordinate of stars ascending X coordinate.

So we can avoid the sort calculated directly in the loop input:

for(int i=1;i<=n;i++)
    {
        scanf("%d%d",&x,&y);
        level[sum(++x)]++;
        add(x,1);
    }

Wherein the level array used to count the number of stars in the class of each one of 0-N.

Then let us look at the standard lowbit function and the sum function tree array:

int sum(int x)
{
    int ans=0;
    while(x>0)
    {
        years + = a [x];
        x-=lowbit(x);
    }
    return ans;
}
int lowbit(int x)
{
    return x&-x;
}

So that we facilitate the statistical calculation lag, given the full AC in the following code:

#include<cstdio>
using namespace std;
const int maxn=32005;
int a[maxn],level[maxn],n,x,y;
int lowbit(int x)
{
    return x&-x;
}
void add(int x,int v)
{
    while(x<=maxn)
    {
        a[x]+=v;
        x+=lowbit(x);
    }    
}
int sum(int x)
{
    int ans=0;
    while(x>0)
    {
        years + = a [x];
        x-=lowbit(x);
    }
    return ans;
}
int main ()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%d%d",&x,&y);
        level[sum(++x)]++;
        add(x,1);
    }
    for(int i=0;i<=n-1;i++) printf("%d\n",level[i]);    
    return 0;
}

Guess you like

Origin www.cnblogs.com/Warframe-Gauss/p/12114956.html