福州大學OJ 2260-Card Game (單調棧+DP)

題目:

有如下取牌遊戲:

  1. 桌面上有n張卡牌從左到右排成一行,每張卡牌上有一個數字;

  2. 遊戲按輪次進行,每一輪中取掉所有比左邊數值小的卡牌;

  3. 當無牌可取的時候則遊戲結束。

比如初始卡牌爲{5, 6, 3, 7, 4, 1, 2},共需2輪取牌。取牌過程如下(小括號爲每輪取掉的牌):

{5, 6, 3, 7, 4, 1, 2}

==> {5, 6, (3), 7, (4), (1), 2}

==> {5, 6, 7, 2}

==> {5, 6, 7, (2)}

==> {5, 6, 7}

現按順序給定初始的卡牌數字,請求出遊戲結束時取牌的總輪次,並輸出結束時桌上剩餘的卡牌序列。

Input
包含多組測試數據。

輸入包含兩行。

第一行包含一個整數n表示卡牌的數量。

第二行包含n個空格隔開的整數,表示排成一行的卡牌上對應的數字(取值範圍[1,1000000000])。

n≤1000000

Output
輸出包含兩行。

第一行包含一個整數表示遊戲的取牌總輪次。

第二行包含遊戲結束時桌上剩餘的卡牌序列,用空格隔開。

Sample Input
7
5 6 3 7 4 1 2
Sample Output
2
5 6 7

代碼:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
#include <climits>
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = INT_MAX;
const int maxn = 1000000+5;
int T,n,m;
int ans,k;
int a[maxn],res[maxn];
int dp[maxn];//dp[i]表示下標爲i的元素被取出去的輪數
stack<int>st;

int main()
{
    while(scanf("%d",&n)!=EOF)
    {
        ans=k=0;
        memset(dp,0,sizeof(dp));
        memset(res,0,sizeof(res));
        for(int i=0;i<n;i++)
            scanf("%d",&a[i]);
        for(int i=0;i<n;i++)
        {
            while(!st.empty()&&a[st.top()]<=a[i])
            {
                if(st.size()==1)//如果當前棧內只有一個元素 這個元素一定是最後剩下的
                    res[k++] = a[st.top()];
                else//如果棧內不止一個元素,那麼棧頂的元素一定是可以取出的
                {
                    dp[i]=max(dp[i],dp[st.top()]+1);
                    ans=max(ans,dp[i]);
                }
                st.pop();
            }
            st.push(i);
        }
        while(st.empty()==0)
        {
            if(st.size()==1)
                res[k++] = a[st.top()];
            else
                ans=max(ans,dp[st.top()]+1);
            st.pop();
        }
        printf("%d\n",ans);
        for(int i=0;i<k;i++)
        {
            if(i==0)
                printf("%d",res[i]);
            else
                printf(" %d",res[i]);
        }
        printf("\n");
    }
    return 0;
}
發佈了90 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章