1392D 1700
题意:给你一个长度为n的字符串只包含L和R,表示当前位置的人攻击左边或者右边的人,同时1的左边是n,1的右边是2,如果当前位置只被左边或者右边的人攻击,那么他要攻击其左边或右边的人作为回应,即相互攻击,如果既被左边又被右边的人攻击,那么其可以攻击任意一个人,这样的字符串才是合法的,问至少要操作多少次才能使字符串合法。
思路:首先要对这个字符串进行处理,因为要把这个字符串当成一个环来看待,可以先预处理一波,之后就是如果存在连续的三个或三个以上相同的字母,那么这个片段肯定是不合理的,(一个肯定合理,两个也合理RRL),那么对于这个长度为cnt的字符串至少要操作cnt/3次。但是有一个特殊点要注意,如果这个字符串的字母是全部相同的话要cnt/3向上取整,即(cnt+2)/3。具体实现可看代码
代码如下:
#pragma GCC optimize("Ofast","inline","-ffast-math")
#pragma GCC target("avx,sse2,sse3,sse4,mmx")
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
#define rep(i, a, n) for(int i = a; i <= n; i++)
#define per(i, a, n) for(int i = n; i >= a; i--)
#define IOS std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
#define fopen freopen("file.in","r",stdin);freopen("file.out","w",stdout);
#define fclose fclose(stdin);fclose(stdout);
const int inf = 1e9;
const ll onf = 1e18;
const int maxn = 1e5+10;
inline int read(){
int x=0,f=1;char ch=getchar();
while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}
while (isdigit(ch)){x=(x<<3)+(x<<1)+ch-48;ch=getchar();}
return x*f;
}
inline void cf(){
int t = read();
while(t--){
int n = read();
string s;cin>>s;
int cnt = 0;
while(s[0]==s[n-1]&&n){
n--;
cnt++;
}
if(n==0){
if(cnt<=2) {printf("0\n");continue;}
else {printf("%d\n", (cnt+2)/3);continue;}
}
s[n]='$'; n++; // 注意最后插入一个不会在字符串中出现的字母
int ans = 0;
for(int i = 0; i < n-1; i++){
cnt++;
if(s[i]!=s[i+1]){
ans += cnt/3;
cnt=0;
}
}
printf("%d\n", ans);
}
return ;
}
signed main(){
cf();
return 0;
}