CF1912L 题解

发布时间 2023-12-21 21:24:43作者: shimingxin1007

原题传送门


题目大意

有一个仅有 0L 构成的序列,求出一种方案,使得左部分的 0 数量不等于右部分的 O 数量,且左部分的 L 数量不等于右部分的 L 数量,若不存在输出 -1

思路分析

首先看题目范围,\(2≤n≤200\),数据很小,考虑暴力。

可以使用字符串截取函数 s.substr()

本题我们使用其两种使用方法:

  • s.substr(idx,len) 截取下标为 \(idx\) 之后(包括 \(idx\))的 \(len\) 位元素。

  • s.substr(idx) 截取下标为 \(idx\) 一直到字符串最后的所有元素。

针对此题,第一种方法可截取左部分,第二种方法可截取有部分,按照题意模拟即可。

该思路的时间复杂度为 \(\mathcal{O(n^2)}\)

代码:

/*Written by smx*/
#include<bits/stdc++.h>
using namespace std;
bool check(string a,string b){
	int La=0,Lb=0,ZEROa=0,ZEROb=0;
	for(int i=0;i<a.size();i++){
		if(a[i]=='L'){
			La++;
		}
		else{
			ZEROa++;
		}
	}
	for(int i=0;i<b.size();i++){
		if(b[i]=='L'){
			Lb++;
		}
		else{
			ZEROb++;
		}
	}
	return La!=Lb&&ZEROa!=ZEROb;
}
int main()
{
	//freopen(".in","r",stdin);
	//freopen(".out","w",stdout);
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int len;
	string s;
	cin>>len>>s;
	for(int i=0;i<s.size()-1;i++){//枚举分割位置
		string strl,strr;
		strl=s.substr(0,i+1);
		strr=s.substr(i+1);
		if(check(strl,strr)){
			cout<<i+1;
			return 0;
		}
	}
	cout<<"-1";
	return 0;
}