Codeforces Round #658 (Div. 2) D. Unmerge(分块,背包dp)

题目传送
思路:
首先得观察到一个规律,如果某个数的后面紧跟着的数中有一段比他小的数,那么这一段数肯定是在一个数组中的,例: 5 3 1 4 2 10 7 8 9 6 ,那么可以分成三段 [5 3 1] ,[4 2] ,[10 7 8 9 6],那么分段有什么意义呢?

我们知道了可以把这些段分出来,那么我们现在就可以把段自由组合一下,如果能组合成一个长度为n的数组,那么就成立了,如何自由组合?这很像背包dp,代价为段的长度,价值也为段的长度

AC代码

#include <bits/stdc++.h>
inline long long read(){char c = getchar();long long x = 0,s = 1;
while(c < '0' || c > '9') {if(c == '-') s = -1;c = getchar();}
while(c >= '0' && c <= '9') {x = x*10 + c -'0';c = getchar();}
return x*s;}
using namespace std;
#define NewNode (TreeNode *)malloc(sizeof(TreeNode))
#define Mem(a,b) memset(a,b,sizeof(a))
#define lowbit(x) (x)&(-x)
const int N = 4e3 + 5;
const long long INFINF = 0x7f7f7f7f7f7f7f;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-7;
const int mod = 1e9+7;
const double II = acos(-1);
const double PP = (II*1.0)/(180.00);
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> piil;
signed main()
{
    std::ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    //    freopen("input.txt","r",stdin);
    //    freopen("output.txt","w",stdout);
    int t;
    cin >> t;
    while(t--)
    {
        int ans[N],arr[N],dp[N] = {0},n,m = 0;
        cin >> n;
        for(int i = 1;i <= 2*n;i++) cin >> arr[i];
        int Max = arr[1],num = 1;
        for(int i = 2;i <= 2*n;i++)
        {
            if(arr[i] > Max)
                {Max = arr[i];ans[m++] = num;num = 0;}
            num++;
        }
        for(int i = 0;i < m;i++)
            for(int j = n;j >= ans[i];j--)
                dp[j] = max(dp[j],dp[j-ans[i]]+ans[i]);
        dp[n] == n ? cout << "YES" << endl : cout << "NO" << endl;
    }
}

猜你喜欢

转载自blog.csdn.net/moasad/article/details/107519674