1480 D1. Painting the Array I(贪心)

传送门

题目大意

把数组 a a a分成两个不相交的子数组 a 0 a^0 a0 a 1 a^1 a1

要求 s e g ( a 0 ) seg(a^0) seg(a0) s e g ( a 1 ) seg(a^1) seg(a1)最大

s e g ( a ) seg(a) seg(a)表示数组 a a a中不同的连续段

比如 [ 1 , 2 , 2 , 2 , 2 , 3 , 3 , 1 ] [1,2,2,2,2,3,3,1] [1,2,2,2,2,3,3,1]有四段为 [ 1 , 2 , 3 , 1 ] [1,2,3,1] [1,2,3,1]


考虑贪心

我们记当前 a 0 a^0 a0最前面的元素为 o n e one one, a 1 a^1 a1最前面的元素为 t w o two two

那么 a a a中的每一个元素,我们依次考虑分配给 a 0 a^0 a0更优还是分配给 a 1 a^1 a1更优


o n e = = t w o one==two one==two

显然此时把 a [ i ] a[i] a[i]给哪个子数组都无所谓,随便丢。

o n e ! = a [ i ] & & t w o = = a [ i ] one!=a[i]\&\&two==a[i] one!=a[i]&&two==a[i]

a [ i ] a[i] a[i]丢在 o n e one one后面答案会加一,更优

a [ i ] a[i] a[i]放在 t w o two two后面放弃暂时的收益后续可能更优秀吗??不可能的

末尾什么数字之影响下一次的收益,所以可以让答案加一就先加一,不会使答案变劣。

t w o ! = a [ i ] & & o n e = = a [ i ] two!=a[i]\&\&one==a[i] two!=a[i]&&one==a[i]

同上,把 a [ i ] a[i] a[i]丢在 t w o two two后面更好

o n e ! = t w o & & o n e ! = a [ i ] & & t w o ! = a [ i ] one!=two\&\&one!=a[i]\&\&two!=a[i] one!=two&&one!=a[i]&&two!=a[i]

此时放在哪个位置都会让答案加一,那么怎么选择??

定义 n x t [ i ] nxt[i] nxt[i]为数字 i i i出现最近的位置

如果 n x t [ o n e ] < n x t [ t w o ] nxt[one]nxt[one]<nxt[two],放在 o n e one one后面更优

如果 n x t [ o n e ] > n x t [ t w o ] nxt[one]>nxt[two] nxt[one]>nxt[two],放在 t w o two two后面更优

#include 
using namespace std;
const int maxn = 2e5+10;
int n,a[maxn],id[maxn];
vector<int>vec[maxn];
int main()
{
     
    cin >> n;
    for(int i=1;i<=n;i++)	{
      cin >> a[i]; vec[a[i]].push_back(i); }
	int ans = 0,one = -1,two = -1;
	for(int i=1;i<=n;i++)
	{
     
		id[a[i]]++;
		if( one==two )
		{
     
			if( one!=a[i] )	one = a[i],ans++;
		}
		else if( one!=a[i]&&two==a[i] )	one = a[i],ans++;
		else if( two!=a[i]&&one==a[i] )	two = a[i],ans++;
		else
		{
     
			if( one==-1 )	two = a[i],ans++;
			else if( two==-1 )	one = a[i],ans++;
			else
			{
     
				int nxt_one = n+1, nxt_two = n+1;
				if( id[one]<vec[one].size() )	nxt_one = vec[one][id[one]];
				if( id[two]<vec[two].size() )	nxt_two = vec[two][id[two]];
				if( nxt_one>nxt_two )	two = a[i],ans++;
				else	one = a[i],ans++;
			}
		}
	}
	cout << ans;
}

你可能感兴趣的:(div题解)