G - Two Merged Sequences(dp&贪心)

Posted Harris-H

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了G - Two Merged Sequences(dp&贪心)相关的知识,希望对你有一定的参考价值。

G - Two Merged Sequences(dp&贪心)

思路1.贪心

维护两个序列,若对于当前元素 x x x x x x只能被加进一个序列中那么直接加入。

若都不能加入输出无解。 否则比较后一个元素 y y y

x > y x>y x>y 显然 x x x加入降序,更优。因为如果 x x x加入升序,那么 y y y只能加入降序。

x x x加入降序, x x x后面可以加入更多数,且升序序列也能加入更多数。

x < y x<y x<y显然 x x x加入升序,更优。证明同理。

时间复杂度: O ( n ) O(n) O(n)

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

int main() 
	int n;
	cin >> n;
	int a[n];
	for (int i = 0; i < n; i++)
		cin >> a[i];
	int inc = -1, dec = 1e9;
	for (int i = 0; i < n; i++)
		if (inc < a[i] && (a[i] < a[i + 1] || a[i] >= dec))
			inc = a[i], a[i] = 0;
		else if (dec > a[i])
			dec = a[i], a[i] = 1;
		else
			return cout << "NO\\n", 0;
	cout << "YES\\n";
	for (int i = 0; i < n; i++)
		cout << a[i] << ' ';

思路2 dp

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int inf = 0x7f7f7f7f;
int a[200005];
int dp[200005][2];
int op[200005][2];
int opt[200005];
int main()

    int n;
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
        scanf("%d", &a[i]);
    dp[1][1] = inf, dp[1][0] = -inf;
    for (int i = 2; i <= n; i++)
    
        dp[i][1] = -inf, dp[i][0] = inf;
        if (a[i - 1] < a[i] && dp[i][1] < dp[i - 1][1])
        
            dp[i][1] = dp[i - 1][1];
            op[i][1] = 1;
        
        if (dp[i - 1][0] < a[i] && dp[i][1] < a[i - 1])
        
            dp[i][1] = a[i - 1];
            op[i][1] = 0;
        
        if (a[i - 1] > a[i] && dp[i][0] > dp[i - 1][0])
        
            dp[i][0] = dp[i - 1][0];
            op[i][0] = 0;
        
        if (dp[i - 1][1] > a[i] && dp[i][0] > a[i - 1])
        
            dp[i][0] = a[i - 1];
            op[i][0] = 1;
        
    
    if (dp[n][1] != -inf)
    
        printf("YES\\n");
        for (int i = n, optmp = 1; i >= 1; i--)
        
            opt[i] = optmp;
            optmp = op[i][optmp];
        
        for (int i = 1; i <= n; i++)
        
            printf("%d ", opt[i] != 1);
        
    
    else if (dp[n][0] != inf)
    
        printf("YES\\n");
        for (int i = n, optmp = 0; i >= 1; i--)
        
            opt[i] = optmp;
            optmp = op[i][optmp];
        
        for (int i = 1; i <= n; i++)
        
            printf("%d ", opt[i] != 1);
        
    
    else
        printf("NO");
    return 0;

以上是关于G - Two Merged Sequences(dp&贪心)的主要内容,如果未能解决你的问题,请参考以下文章

G - Two Merged Sequences(dp&贪心)

G - Two Merged Sequences(dp&贪心)

Two Merged Sequences 贪心

Codeforces 1144G Two Merged Sequences dp

arc092D Two Sequences

AtCoderARC092 D - Two Sequences