【题目链接】C题链接

【题目类型】贪心、模拟

【题目大意】有t个测试样例。现在给你长度为n的字符串,要求你通过

In one operation you can choose any consecutive substring of s and reverse it. In other words, you can choose any substring s[l…r]=sl,sl+1,…,sr and change the order of elements in it into sr,sr−1,…,sl.

倒序操作使得最外层括号匹配有k个。最后输出你的操作总数和操作了那些位置。

【解题思路】
(1)先看一下输入(只拿一个样例来看)
input
10 3
))()()()((
我要达成最外层有三个,那直接把前面四个字符更改成了()() 然后再加上后面一个这个(…),不就可以了吗?(这也就是本题贪心思路所在)
(2)注意题目输出中的这么一句话,

In the first line print integer m (0≤m≤n) — the number of operations. You do not need to minimize m, any value is suitable.

意思是你的操作总数可能是0到n当中的一个数,但是题目并不要求你一定每次的操作数是最少的,于是你可以每次操作数都是最大的,也就是n,那么解题不需要考虑最小操作总数的时候就可以使题目变得简单。

【我的错误的解题思路】我注意到要想前面是()()()()()()()…这个样子的话,前面每个偶数位置(位置按的是数组下标)上的都是 ‘ ( ’,而奇数上的位置都是 ‘)’,这也就使得我想去判断每个位置是否符合条件,如果不符合就去寻找(如果偶数位置不符合,那我就去寻找这个位置后面第一个是‘(’的地方,如果奇数位置不符合,我就去寻找这个位置后面第一个是‘)’的地方,然后进行倒序操作)

这个错误点在哪里呢?虽然没能实现代码,但是我大概清楚错误的地方是这么几个

  1. 时间复杂度会惊人的高,因为你需要进行很多次的查找,外层进行k-1次操作,内层str.size()寻找不符合的地方,找到不符合的地方再去找可以匹配进行倒序的地方(k-1)* (len) (m),最后还需要对最后的一个大括号进行处理(同理要查找)
  2. 最后的大括号的处理会出现问题,假设我要k=5,我需要5个房间,就是你只是处理这加粗的两个位置,而
    ()()()())()(
    如果第一个加粗位置的后一个位置和加粗位置形成了匹配呢?那最后一个大括号变得不成立了吗?

【正确的解题思路】直接先把前面k-1个()先储存起来,后面再加上[n -(k-1)* 2]/2个左括号,以及[n -(k-1)* 2]/2个右括号,差不多是这样的((((…)))),最后拿你这段储存的括号字符去和输入的字符进行比较就好了

注意写的倒序函数,1)你的倒序长度是多少!

/** * This code has been written by YueGuang, feel free to ask me question. Blog: http://www.yx.telstudy.xyz * created: */
#include <cstdio>
#include <iostream>
#include <set>
#include <map>
#include <vector>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
#define rep(i, a, b) for(int i = a; i < b; i++)
#define rep_(i, a, b) for(int i = a; i <= b; i++)
#define rep1(i, n) for(int i = 1; i < n; i++)
#define rep1_(i, n) for(int i = 1; i <= n; i++)
#define pb(x) push_back(x);
#define si(x) scanf("%d", &x);
#define sl(n) scanf("%lld", &n);
#define pi(a) printf("%d\n", a);
#define RepAll(a) for(auto x: a)
#define cout(ans) cout << ans << endl;
typedef long long ll;

using namespace std;
const int maxn = 2048;
/* You do not need to minimize m, any value is suitable.*/
string str;
void rev(int i, int j){
    /* i位置到j位置的字符进行转换*/
    for(int start = 0; start < (j - i + 1)/2; start++){
        swap(str[start + i], str[j - start]);
    }
}

int main(){
    int t; scanf("%d", &t);
    while(t--){
        int k, n;scanf("%d%d",&n, &k);k--;
         cin >> str;
        pi(n);
        string ans;
        rep(i, 0, k){ ans += "()";}
        rep(i, 0, (n - 2 * k) / 2){ans += "(";}
        rep(i, 0, (n - 2 * k) / 2){ans += ")";}
        rep(i, 0, n){
            int p = i;
            while(str[p] != ans[i]){p++;}//查找和i相同的地方
            rev(i, p);
            cout << i+1 << " " << p+1 << '\n';
        }
        }
        return 0;
}