JOIOI の塔 题解

题目传送门

洛谷上竟然还没有题解...

题目分析

简单贪心题。

考虑倒过来寻找。显然,如果一个 J 想要配成一座塔,那么必须要找一个 OIO 更简单,就是直接找到一个 I 放上去就行。

最难的是 I,它既可以选择单开一座塔,也可以选择放在原来的塔上面组成 IOI。然后贪心思考,发现如果塔底的数量少于需求的数量,那么单开一座塔更优,否则放原来的塔更优。

然后就是二分答案,二分所需的塔底数量,跑一遍模拟。

贴上代码

#include<bits/stdc++.h>
#define int long long 
using namespace std;
const int maxn=1e6+5;
int n;
int ans;
int l,r;
string s;
inline void init(){
	cin>>n;cin>>s;s=" "+s;
	l=1;r=n;
}
bool check(int x){
	int res=0,cnt1=0,cnt2=0;
	for(register int i=n;i>=1;--i){
		if(res==x) return true;
		if(s[i]=='J'){
			if(cnt1!=0){
				cnt1--;res++;
			}
		}
		else if(s[i]=='O'){
			if(cnt2!=0){
				cnt2--;cnt1++;
			}
		}
		else{
			if(cnt1+cnt2+res>=x&&cnt1!=0){
				cnt1--;res++;
			}
			else cnt2++;
		}
	}
	if(res==x) return true;
	return false;
}
signed main(){
	init();
	while(l<=r){
		int mid=(l+r)>>1;
		if(check(mid)==true){
			l=mid+1;ans=mid;
		}
		else r=mid-1;
	}
	cout<<ans<<endl;
}
posted @ 2022-11-03 22:24  yizhixiaoyun  阅读(86)  评论(0)    收藏  举报