USACO-Moo Operations

这篇文章描述了一个编程问题,Bessie需要将包含M和O的字符串转换成MOO,要求最小化操作次数。给定一系列字符串,程序需计算最少需要多少次替换或删除操作,或者在不可能的情况下输出-1。提供的C++代码示例用于解决这个问题。
摘要由CSDN通过智能技术生成

题目描述(没有中文!):

Because Bessie is bored of playing with her usual text string where the only characters are 'C,' 'O,' and 'W,' Farmer John gave her Q� new strings (1≤Q≤1001≤�≤100), where the only characters are 'M' and 'O.' Bessie's favorite word out of the characters 'M' and 'O' is obviously "MOO," so she wants to turn each of the Q� strings into "MOO" using the following operations:

  1. Replace either the first or last character with its opposite (so that 'M' becomes 'O' and 'O' becomes 'M').

  1. Delete either the first or last character.

Unfortunately, Bessie is lazy and does not want to perform more operations than absolutely necessary. For each string, please help her determine the minimum number of operations necessary to form "MOO" or output −1−1 if this is impossible.

INPUT FORMAT (input arrives from the terminal / stdin):

The first line of input contains the value of Q�.

The next Q� lines of input each consist of a string, each of its characters either 'M' or 'O'. Each string has at least 1 and at most 100 characters.

OUTPUT FORMAT (print output to the terminal / stdout):

Output the answer for each input string on a separate line.

SAMPLE INPUT:

3

MOMMOM

MMO

MOO

SAMPLE OUTPUT:

4

-1

0

A sequence of 44 operations transforming the first string into "MOO" is as follows:

Replace the last character with O (operation 1)

Delete the first character (operation 2)

Delete the first character (operation 2)

Delete the first character (operation 2)

The second string cannot be transformed into "MOO." The third string is already "MOO," so no operations need to be performed.

代码如下:

#include<bits/stdc++.h>
using namespace std;
int q;
char a[1001]={};
int main(){
	cin>>q;
	while(q--){
		cin>>a;
		int z=strlen(a),s=-1,flag=0;
		for(int i=0;i<z-2;i++){
			if(a[i]=='M'&&a[i+1]=='O'&&a[i+2]=='O'){
				s=z-3;
				break;
			}
			else if(a[i]=='M'&&a[i+1]=='O'&&a[i+2]=='M'){
				if(s<0){
					s=z-2;
				}else{
					s=min(s,z-2);
				}
				
			}
			else if(a[i]=='O'&&a[i+1]=='O'&&a[i+2]=='O'){
				if(s<0){
					s=z-2;
				}else{
					s=min(s,z-2);
				}
			}else if(a[i]=='O'&&a[i+1]=='O'&&a[i+2]=='M'){
				if(s<0){
					s=z-1;
				}else{
					s=min(s,z-1);
				}
			}else{
				if(s<0) s=-1;
			}
			
		}
		cout<<s<<endl;
		
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值