Alter Alter(字符串+思维)

原题链接: https://atcoder.jp/contests/abc174/tasks/abc174_d?lang=en

在这里插入图片描述
测试样例

Sample Input 1
4
WWRR
Sample Output 1
2
例如,下面的两个操作将达到目的。
交换 第1个 和 第3块石头,导致RWWR。 更改 第4个石头,产生RWWW

Sample Input 2
2
RR
Sample Output 2
0
是不需要任何操作的情况。
Sample Input 3
8
WRWWRWRR
Sample Output 3
3

解题思路: 题目的意思就是需要将所有的R都移到最左边去,那么我们换个理解,其实就是让最右边的R和最左边的W交换,最往中间靠拢,直到最右边的R的位置大于最左边的W的位置。那么这个我们可以利用双端队列存储W和R的位置来模拟。 具体看AC代码。

AC代码

/*
*邮箱:unique_powerhouse@qq.com
*blog:https://me.csdn.net/hzf0701
*注:文章若有任何问题请私信我或评论区留言,谢谢支持。
*
*/
#include<bits/stdc++.h>//POJ不支持

#define rep(i,a,n) for(int i=a;i<=n;i++)
#define per(i,a,n) for(int i=a;i>=n;i--)

using namespace std;

const int inf=0x3f3f3f3f;//无穷大。
const int maxn=1e5;//限定值。
typedef long long ll;

int n;
int main(){
	while(cin>>n){
		string s;
		cin>>s;
		deque<int> pos1;
		deque<int> pos2;
		int len=s.size();
		rep(i,0,len-1){
			if(s[i]=='W'){
				pos1.push_back(i+1);
			}
			else{
				pos2.push_back(i+1);
			}
		}
		int cnt=0;
		while(!pos1.empty()&&!pos2.empty()){
			int temp1=pos1.front();
			int temp2=pos2.back();
			if(temp1<temp2){
				cnt++;
				pos1.pop_front();
				pos2.pop_back();
			}
			else{
				break;
			}
		}
		cout<<cnt<<endl;
	}
	return 0;
}
posted @ 2022-03-26 16:49  unique_pursuit  阅读(35)  评论(0)    收藏  举报