Submission #1317756

#TimeUsernameProblemLanguageResultExecution timeMemory
1317756JuanJLGrowing Vegetable is Fun 3 (JOI19_ho_t3)C++20
0 / 100
1 ms332 KiB
#include <bits/stdc++.h>

#define fst first
#define snd second
#define pb push_back
#define forn(i,a,b) for(int i = a; i<b; i++)
#define SZ(x) (int)x.size()
#define ALL(x) x.begin(),x.end()
#define mset(a,v) memset(a,v,sizeof(a))
using namespace std;
typedef long long ll;

	map<char,vector<ll>> pos;
ll nextp(char c, ll i){
	ll res = 1000000;
	if(c!='G'){
		ll ig = lower_bound(ALL(pos['G']),i)-pos['G'].begin();
		if(ig<SZ(pos['G'])) res=min(res,pos['G'][ig]);
	}
	if(c!='Y'){
		ll iy = lower_bound(ALL(pos['Y']),i)-pos['Y'].begin();
		if(iy<SZ(pos['Y'])) res=min(res,pos['Y'][iy]);
	}
	if(c!='R'){
		ll ir = lower_bound(ALL(pos['R']),i)-pos['R'].begin();
		if(ir<SZ(pos['R'])) res=min(res,pos['R'][ir]);
	}
	return res;
}


int main(){
	ll n; cin>>n;
	string s; cin>>s;


	forn(i,0,n) pos[s[i]].pb(i);
	pos['R'].pb(1000000);
	pos['G'].pb(1000000);
	pos['Y'].pb(1000000);

	ll res = 0;

	forn(i,0,n-1){
			if(s[i]==s[i+1]){
				ll j = nextp(s[i],i+1);
			//	cout<<i<<" "<<i+1<<" "<<j<<'\n';
				ll oj = j;
				if(j>=n) continue;
				for(j=oj; j>i+1; j--){
					res++;
					char aux = s[j-1];
					s[j-1]=s[j];
					s[j]=aux;
				}
				pos[s[i+1]].erase(lower_bound(ALL(pos[s[i+1]]),oj));
				pos[s[i+1]].pb(i+1);
				sort(ALL(pos[s[i+1]]));

				//cout<<s<<'\n';
			}
		}
	//cout<<" RES: ";
//	cout<<s<<'\n';
	reverse(ALL(s));
	pos['R'].clear();
	pos['G'].clear();
	pos['Y'].clear();
	forn(i,0,n) pos[s[i]].pb(i);
		pos['R'].pb(1000000);
		pos['G'].pb(1000000);
		pos['Y'].pb(1000000);

	forn(i,0,n-1){
			if(s[i]==s[i+1]){
				ll j = nextp(s[i],i+1);
				ll oj = j;
				if(j>=n) continue;
				for(j=oj; j>i+1; j--){
					res++;
					char aux = s[j-1];
					s[j-1]=s[j];
					s[j]=aux;
				}
				pos[s[i+1]].erase(pos[s[i+1]].begin()+oj);
				pos[s[i+1]].pb(i+1);
				sort(ALL(pos[s[i+1]]));
			}
		}
	//	cout<<s<<'\n';

	bool yes=true;
	forn(i,0,n-1){
		if(s[i]==s[i+1]) yes=false;
	}

	if(yes) cout<<res<<'\n';
	else cout<<-1<<'\n';
	
	return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...