CodeForces - 548D Mike and Feet(單調棧)

題意:給出n個數,假設區間長度爲k,給定一個起點求區間最小值,由於有很多起點,所以要求的是這些的最大值。然後k的範圍是1-n。。(感覺好彆扭)。所以要輸出n個答案。

做法:我們都知道單調棧可以處理出一個數爲最小值的最長區間,那麼先處理出這個東西。再把數字帶着他的最長區間降序排個序。設指針p爲1,我們可以發覺對於區間長度從小到大來說答案是不增的,所以如果當前數字最長區間爲x,那麼我們只需要更新p到x爲這個數。因爲小於p的區間長度已經是當前數字之前數字爲答案了(比當前大)。

AC代碼:

#pragma comment(linker, "/STACK:102400000,102400000")
#include<cstdio>
#include<ctype.h>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<vector>
#include<cstdlib>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<cmath>
#include<ctime>
#include<string.h>
#include<string>
#include<sstream>
#include<bitset>
using namespace std;
#define ll __int64
#define ull unsigned long long
#define eps 1e-8
#define NMAX 10000000
#define MOD 1000000007
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define PI acos(-1)
#define mp make_pair
template<class T>
inline void scan_d(T &ret)
{
    char c;
    int flag = 0;
    ret=0;
    while(((c=getchar())<'0'||c>'9')&&c!='-');
    if(c == '-')
    {
        flag = 1;
        c = getchar();
    }
    while(c>='0'&&c<='9') ret=ret*10+(c-'0'),c=getchar();
    if(flag) ret = -ret;
}
const int maxn = 200000+10;
int st[maxn][2],a[maxn];
struct node
{
    int val,ran;
    bool operator < (const node &t) const
    {
        return val > t.val;
    }
}no[maxn];
int l[maxn],r[maxn];
int ans[maxn];
int main()
{
#ifdef GLQ
    freopen("input.txt","r",stdin);
//    freopen("o.txt","w",stdout);
#endif
    int n;
    scanf("%d",&n);
    for(int i = 1; i <= n; i++)
    {
        scanf("%d",&a[i]);
        no[i].val = a[i];
    }
    int top = 0;
    st[0][0] = st[0][1] = 0;
    for(int i = 1; i <= n; i++)
    {
        while(a[i] <= st[top][0]) top--;
        l[i] = st[top][1]+1;
        st[++top][0] = a[i];
        st[top][1] = i;
    }
    top = 0;
    st[0][0] = 0;
    st[0][1] = n+1;
    for(int i = n; i >= 1; i--)
    {
        while(a[i] <= st[top][0]) top--;
        r[i] = st[top][1]-1;
        st[++top][0] = a[i];
        st[top][1] = i;
    }
    for(int i = 1; i <= n; i++)
    {
        no[i].ran = r[i]-l[i]+1;
    }
    sort(no+1,no+1+n);
    int p = 1;
    for(int i = 1; i <= n; i++)
    {
        if(no[i].ran < p) continue;
        while(p <= no[i].ran)
            ans[p++] = no[i].val;
    }
    for(int i = 1; i <= n; i++)
        printf("%d%c",ans[i],(i==n)?'\n':' ');
    return 0;
}


發佈了187 篇原創文章 · 獲贊 9 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章