51 nod 1272 最大距离(树状数组)

来源:互联网 发布:如何注销知乎账号 编辑:程序博客网 时间:2024/05/17 09:11

1272 最大距离
题目来源: Codility
基准时间限制:1 秒 空间限制:131072 KB 分值: 20 难度:3级算法题
 收藏
 关注
给出一个长度为N的整数数组A,对于每一个数组元素,如果他后面存在大于等于该元素的数,则这两个数可以组成一对。每个元素和自己也可以组成一对。例如:{5, 3, 6, 3, 4, 2},可以组成11对,如下(数字为下标):
(0,0), (0, 2), (1, 1), (1, 2), (1, 3), (1, 4), (2, 2), (3, 3), (3, 4), (4, 4), (5, 5)。其中(1, 4)是距离最大的一对,距离为3。
Input
第1行:1个数N,表示数组的长度(2 <= N <= 50000)。第2 - N + 1行:每行1个数,对应数组元素Ai(1 <= Ai <= 10^9)。
Output
输出最大距离。
Input示例
6536342
Output示例
3


题目给的提示是单调队列 我tm根本不睬他直接用树状数组艹了过去

然后又和大神学了一下O(n)的做法 就是排个序维护位置的最小值

#include<iostream>#include<algorithm>#include<cstdio>#include<cstdlib>#include<cstring>#include<vector>#include<map>#include <bits/stdc++.h>using namespace std;const int N = 300000+10;typedef  long long LL;const LL mod = 998244353;int a[N],b[N],c[N];void add(int x,int h,int n){    while(x<=n)    {        c[x]=min(c[x],h);        x+=(x&(-x));    }    return ;}int get(int x){    int y=0x3f3f3f3f;    while(x)    {        y=min(c[x],y);        x-=(x&(-x));    }    return y;}int main(){    int n, k;    scanf("%d",&n);    for(int i=1;i<=n;i++) scanf("%d", &a[i]),b[i]=a[i];    sort(b+1,b+n+1);    k=unique(b+1,b+n+1)-(b+1);    memset(c,0x3f3f3f3f,sizeof(c));    int ans=0;    for(int i=1;i<=n;i++)    {        int pos=lower_bound(b+1,b+k+1,a[i])-(b);        add(pos,i,n);        ans=max(ans,i-get(pos));    }    cout<<ans<<endl;    return 0;}

#include<iostream>#include<algorithm>#include<cstdio>#include<cstdlib>#include<cstring>#include<vector>#include<map>#include <bits/stdc++.h>using namespace std;const int N = 300000+10;typedef  long long LL;const LL mod = 998244353;int a[N],c[N];struct node{    int x, y;    bool operator <(const node &A)const    {        if(x!=A.x) return x<A.x;        return y<A.y;    }}b[N];int main(){    int n, k;    scanf("%d",&n);    for(int i=1;i<=n;i++) scanf("%d", &a[i]),b[i].x=a[i],b[i].y=i;    sort(b+1,b+n+1);    int pos, ans=0;    for(int i=1;i<=n;i++)    {        if(i!=1) pos=min(pos,b[i].y);        else pos=b[i].y;        ans=max(ans,b[i].y-pos);    }    cout<<ans<<endl;    return 0;}