CF1634A Reverse and Concatenate 题解

· · 题解

这一题就是判断回文。

显然答案最多为 2。考虑如果 s 是回文串,那么就有 rev(s)+s=s+rev(s)=s+s,那么答案为 1;否则答案为 2。当然还有一种情况:k=0 时答案一定为 1

这一题可以使用 algorithm 库中的 std::reverse 函数。它可以将一个字符串倒置并赋值给该字符串,可以反转 [st,ed) 范围内的元素。然后就可以使用该函数来判断给定字符串是否是回文串。

放代码:

#include<bits/stdc++.h>
using namespace std;
bool pd(string s){
  string s1=s;
  reverse(s.begin(),s.end()); // 反转字符串
  return s1==s;
}
int main(){
  ios::sync_with_stdio(false);
  int t; cin>>t;
  while(t--){
    int n,k; string s; cin>>n>>k>>s;
    if(pd(s)||!k)cout<<"1\n";
    else cout<<"2\n";
  }
  return 0;
}