【BZOJ 2457】 双端队列

【题目链接】

             https://www.lydsy.com/JudgeOnline/problem.php?id=2457

【算法】

           贪心

【代码】

             

#include<bits/stdc++.h>
using namespace std;
#define MAXN 200010

int i,n,len,last,cnt;
int d[MAXN],tmp[MAXN],mx[MAXN],nx[MAXN];
bool flag;

inline bool cmp(int a,int b)
{
        return (d[a] == d[b]) ? (a < b) : (d[a] < d[b]);        
}

int main() 
{
        
        scanf("%d",&n);
        for (i = 1; i <= n; i++) 
        {
                scanf("%d",&d[i]);
                tmp[i] = i;
        }
        sort(tmp+1,tmp+n+1,cmp);
        d[0] = -1;
        for (i = 1; i <= n; i++)
        {
                if (d[tmp[i]] != d[tmp[i-1]]) 
                {
                        len++;
                        nx[len] = mx[len] = tmp[i];        
                }    else 
                {
                        nx[len] = min(nx[len],tmp[i]);
                        mx[len] = max(mx[len],tmp[i]);
                }
        }
        flag = false;
        cnt = 1;
        last = nx[1];
        for (i = 2; i <= len; i++)
        {    
                if (flag && nx[i] < last)
                {
                        flag = false;
                        cnt++;
                        last = nx[i];
                        continue;
                }
                if (!flag && mx[i] > last)
                {
                        flag = true;
                        last = mx[i];
                        continue;
                }
                if (!flag && mx[i] < last) 
                {
                        last = nx[i];
                        continue;
                }
                if (flag && nx[i] > last) last = mx[i];
        }
        printf("%d\n",cnt);
        
        return 0;
    
}

 

posted @ 2018-06-30 15:37  evenbao  阅读(148)  评论(0编辑  收藏  举报