3 solutions

  • 2
    @ 2025-7-5 15:58:29

    考虑到 n≤5000n \le 5000,可以接受 O(n2)O(n^2) 做法,所以遍历 kk,每遇到一个 BB 就将当前位置开头的区间位置反转,后面的数不足 kk 个即无解。

    暴力反转时间复杂度 O(n3)O(n^3),差分优化后时间复杂度 O(n2)O(n^2)

    参考代码:

    #include<iostream>
    #include<queue>
    
    using namespace std;
    
    const int N = 5010;
    int n, k, m = 1e9, cnt;
    char c; bool a[N];
    queue<int> q;
    
    int main(){
    	cin >> n;
    	for(int i = 1; i <= n; i++){
    		cin >> c;
    		a[i] = (c == 'B');
    	}
    	for(int i = 1; i <= n; i++){
    		cnt = 0;
    		for(int j = 1; j <= n; j++){
    			if(q.size() && q.front() + i <= j) q.pop();
    			if((q.size()&1)^a[j]){
    				if(j > (n-i+1)){
    					cnt = 1e9;
    					break;
    				}
    				else{
    					q.push(j);
    					cnt++;
    				}
    			}
    		}
    		if(cnt < m){
    			m = cnt;
    			k = i;
    		}
    		while(q.size()) q.pop();
    	}
    	cout << k << ' ' << m << '\n';
    	return 0;
    }
    

    Information

    ID
    10
    Time
    1000ms
    Memory
    256MiB
    Difficulty
    4
    Tags
    # Submissions
    34
    Accepted
    10
    Uploaded By