Kobolds and Catacombs 思维,模拟,前缀,后缀(沈阳)

在这里插入图片描述
题意 :

  • 给一序列,将其分为若干段,要求每一小段内排序后整体非递减,求最多能分为多少段

思路 :

  • 对一段内部,必然有最大值和最小值,要让分的段数最多,只要让下一段的最小值大于这段的最大值,就可以多分一段
  • 所以直接找每个数能接受的最大值和最小值
  • 即找这个数往前的最大值,下个数往后的最小值(找时注意设立两个哨兵)
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#define debug(a) cout << #a << " = " << a << endl;
#define x first
#define y second
using namespace std;
typedef long long ll;

const int N = 1e6 + 10;

int n;
int a[N];
int maxx[N], minn[N];

int main()
{
    
    
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    
    int _ = 1;
//    cin >> _;

    while (_ -- )
    {
    
    
        cin >> n;
        for (int i = 1; i <= n; i ++ ) cin >> a[i];
        
        maxx[0] = 0;
        minn[n + 1] = 1e9 + 7;
        
        for (int i = 1; i <= n; i ++ )
            maxx[i] = max(maxx[i - 1], a[i]);
        for (int i = n; i >= 1; i -- )
            minn[i] = min(minn[i + 1], a[i]);
        
        int ans = 0;
        for (int i = 1; i <= n; i ++ )
            if (maxx[i] <= minn[i + 1])
                ans ++ ;
        
        cout << ans << endl;
    }
    
    return 0;
}

  • 附上另一种方案,只记录后缀的,且不增加哨兵
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#define debug(a) cout << #a << " = " << a << endl;
#define x first
#define y second
using namespace std;
typedef long long ll;

const int N = 1e6 + 10;

int n;
int a[N];
int maxx[N], minn[N];

int main()
{
    
    
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    
    int _ = 1;
//    cin >> _;

    while (_ -- )
    {
    
    
        cin >> n;
        for (int i = 1; i <= n; i ++ ) cin >> a[i];
        
        int mi = a[n];
        for (int i = n; i >= 1; i -- )
        {
    
    
            mi = min(mi, a[i]);
            minn[i] = mi;
        }
        
        int mx = 0, ans = 0;
        for (int i = 1; i <= n; i ++ )
        {
    
    
            if (mx <= minn[i]) ans ++ ;
            mx = max(mx, a[i]);
        }
        
        cout << ans << endl;
    }
    
    return 0;
}

Guess you like

Origin blog.csdn.net/m0_51448653/article/details/121260744