首页 > 其他分享 >Painting the Array I

Painting the Array I

时间:2023-01-06 23:55:59浏览次数:52  
标签:const int 元素 ed0 ed1 数组 Array Painting

[Painting the Array I](贪心入门 - Virtual Judge (vjudge.net))

题解:

要使得数组a分成的两个数组长度之和最长,我们设\(a^{(0)}\)数组末尾元素为\(ed0\),\(a^{(1)}\)数组末尾元素为\(ed1\),一开始两个数组都为空,所以ed0=ed1=0(题目告诉你空数组长度为0),我们在模拟过后会发现出现了三种情况:

第一种情况:ed0==ed1,但是下一个加进来的元素x!=ed0 && x!=ed1
    x = 1
ed0:0
ed1:0
虽然我们无论如果放在那个数组末尾,都能使贡献+1,但是我们需要关注ed0,ed1在后面还会不会出现,并且谁会先出现
    x = 3 1 1 2
ed0:1
ed1:2
显然这样一定要把3放在ed0,不然就会出现这样的情况,导致贡献-1,所以如果ed0比ed1在后面会先出现,我们将x变为ed0,否则变为ed1
ed0:1 1
ed1:3 1 
第二种情况:下一个加进来的元素x==ed0 && x!=ed1
    x = 1
ed0:1
ed1:2
那很显然我们必须放在ed1后面
第三种情况:下一个加进来的元素x!=ed0 && x==ed1
    x = 1
ed0:2
ed1:1
那很显然我们必须放在ed0后面

那么知道了模拟过程,我们怎么快速找出某个元素的下一个会出现的下标位置呢,1.二分;2.我们可以使用队列

#include <bits/stdc++.h>
#define Zeoy std::ios::sync_with_stdio(false), std::cin.tie(0), std::cout.tie(0)
#define all(x) (x).begin(), (x).end()
#define endl '\n'
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9 + 7;
const double eps = 1e-9;
const int N = 1e5 + 10;
ll a[N];
queue<int> q[N];
int main(void)
{
    Zeoy;
    int t = 1;
    // cin >> t;
    while (t--)
    {
        int n;
        cin >> n;
        for (int i = 1; i <= n; ++i)
        {
            cin >> a[i];
            q[a[i]].push(i);        //存放每个元素出现的位置
        }
        int ed0 = 0, ed1 = 0;
        q[0].push(inf);             //如果后面没有元素了,直接加上inf
        ll ans = 0;
        for (int i = 1; i <= n; ++i)
        {
            q[a[i]].pop();
            q[a[i]].push(inf);      //如果后面没有元素了,直接加上inf
            if (a[i] != ed0 && a[i] != ed1)
            {
                if (q[ed0].front() < q[ed1].front())
                    ed0 = a[i];
                else
                    ed1 = a[i];
                ans++;
            }
            else if (a[i] != ed0 && a[i] == ed1)
            {
                ed0 = a[i];
                ans++;
            }
            else if (a[i] == ed0 && a[i] != ed1)
            {
                ed1 = a[i];
                ans++;
            }
        }
        cout << ans << endl;
    }
    return 0;
}

标签:const,int,元素,ed0,ed1,数组,Array,Painting
From: https://www.cnblogs.com/Zeoy-kkk/p/17031959.html

相关文章