[USACO18OPEN] Out of Sorts G

Topic description:

Two-way bubbling, ask a few times to be able to arrange

Topic Analysis:

Sort the array first. For each position, find out how many numbers are not in the top i after sorting.
Take Max as the answer.
Why?
Bubble sort is exchange
. Each bubbling will make a person who does not belong to the front go to the back, and at the same time let a person who does not belong to the back come to the front, each time it can make the number -1, then take Max as the answer

Topic link:

BZOJ 4375
Luogu 4375

AC code:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#define lowbit(x) ((x&(-x)))
const int maxm=110000; 
struct node{
    int val,id;
}a[maxm];
int sum[maxm],n;
inline bool comp(node x,node y)
{
    return x.val<y.val;
}
inline void ins(int x)
{
    for(int i=x;i<=maxm;i+=lowbit(i))
     sum[i]++;
}
inline int ask(int x)
{
    int res=0;
    for(int i=x;i;i-=lowbit(i))
     res+=sum[i];
    return res;
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
     scanf("%d",&a[i].val),a[i].id=i;
    std::sort(a+1,a+n+1,comp);
    int ans=0;
    for(int i=1;i<=n;i++) 
    {
        ins(a[i].id);
        ans=std::max(ans,i-ask(i));
    }
    printf("%d\n",std::max(ans,1));
    return 0;
}

Guess you like

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