打卡信奥刷题(723)用C++信奥P9012[普及组/提高] [USACO23JAN] Moo Operations B
[USACO23JAN] Moo Operations B
题面翻译
题目描述
农夫约翰给了奶牛贝西 QQQ 个新字符串 (1≤Q≤100)(1\le Q\le100)(1≤Q≤100) ,其中只有字符 M 和 O ,她想将 QQQ 个字符串都变成 MOO。
贝西可以用如下的方式改变字符串:
- 用相反的字符替换第一个或最后一个字符(将
M变成O,将O变成M)。 - 删除第一个或最后一个字符。
贝西只想用最少的次数完成改变。请你帮她找到需要的最小改变次数。如果不可能在有限的步数中完成这个任务,请输出 -1 。
输入格式
输入数据的第一行是一个正整数 QQQ 。
接下来的 QQQ 行中,每行一个只包含大写字母 M 或 O 的字符串 SSS ,保证 $ 1\le |S| \le 100$ 。
输出格式
输出 QQQ 行,每行为该测试点最小操作次数,如果不可能在有限的步数中完成这个任务,请输出 -1 。
提示
样例解释 1
将第一个字符串转换为 MOO的 444 个操作序列如下:
- 用O替换最后一个字符(操作1)
- 删除第一个字符(操作2)
- 删除第一个字符(操作2)
- 删除第一个字符(操作2)
可以证明,第二个字符串无法转换为 MOO。
第三个字符串已经是 MOO,因此无需执行任何操作。
数据范围
对于 100%100\%100% 的测试点,保证 1≤Q≤1001 \le Q \le 1001≤Q≤100, $ 1\le |S| \le 100$ 。
题目描述
Because Bessie is bored of playing with her usual text string where the only characters are C, O, and W, Farmer John gave her QQQ new strings (1≤Q≤100)(1 \le Q \le 100)(1≤Q≤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 QQQ strings into MOO using the following operations:
- Replace either the first or last character with its opposite (so that ‘M’ becomes ‘O’ and ‘O’ becomes ‘M’).
- 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−1 if this is impossible.
输入格式
The first line of input contains the value of QQQ.
The next QQQ lines of input each consist of a string, each of its characters either M or O. Each string has at least 111 and at most 100100100 characters.
输出格式
Output the answer for each input string on a separate line.
样例 #1
样例输入 #1
3
MOMMOM
MMO
MOO
样例输出 #1
4
-1
0
提示
Explanation for Sample 1
A sequence of 444 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.
Scoring
- Inputs 2−42-42−4: Every string has length at most 333.
- Inputs 5−115-115−11: No additional constraints.
C++实现
#include<bits/stdc++.h>
using namespace std;
signed main()
{
int t;
cin>>t;
while(t–){
int mi=0x3f3f3f3f;
string st;
cin>>st;
if(st.size()❤️){
puts(“-1”);
continue;
}
for(int i=0;i<st.size()-2;i++){
string str=st.substr(i,3);
if(str==“MOO”)mi=min(mi,0);
else if(str==“MOM”)mi=min(mi,1);
else if(str==“OOO”)mi=min(mi,1);
else if(str==“OOM”)mi=min(mi,2);
}
if(mi==0x3f3f3f3f)puts(“-1”);
else cout<<mi+st.size()-3<<‘\n’;
}
}

后续:
接下来我会不断用C++来实现信奥比赛中的算法题、C++考级编程题实现、白名单赛事考题实现,感兴趣的请关注,我后续将继续分享相关内容
更多推荐



所有评论(0)