1. 程式人生 > >[程式設計練習] POJ 3276 Face The Right Way

[程式設計練習] POJ 3276 Face The Right Way

Description

Farmer John has arranged his N (1 ≤ N ≤ 5,000) cows in a row and many of them are facing forward, like good cows. Some of them are facing backward, though, and he needs them all to face forward to make his life perfect.

Fortunately, FJ recently bought an automatic cow turning machine. Since he purchased the discount model, it must be irrevocably preset to turn K (1 ≤ K ≤ N) cows at once, and it can only turn cows that are all standing next to each other in line. Each time the machine is used, it reverses the facing direction of a contiguous group of K cows in the line (one cannot use it on fewer than K cows, e.g., at the either end of the line of cows). Each cow remains in the same location

as before, but ends up facing the opposite direction. A cow that starts out facing forward will be turned backward by the machine and vice-versa.

Because FJ must pick a single, never-changing value of K, please help him determine the minimum value of K that minimizes the number of operations required by the machine to make all the cows face forward. Also determine M, the minimum number of machine operations required to get all the cows facing forward using that value of K.

Input

Line 1: A single integer: N Lines 2…N+1: Line i+1 contains a single character, F or B, indicating whether cow i is facing forward or backward.

Output

Line 1: Two space-separated integers: K and M

Sample Input

7 B B F B F B B

Sample Output

3 3

思路

  • 這道題為反轉(開關)問題,比較暴力的解法是從第一隻牛開始,依次判斷其朝向,若反向,則需將從該牛開始的連續 K 只牛反轉(K=1,2,3… N),時間複雜度 O(N3
    ),N取5000時,超時。
  • 改進:設立一個狀態記錄陣列f[n+1], f[i] 記錄第 i 只牛與第 i-1 只牛朝向的相對位置的值 (i=0時,設為初始狀態‘ F’),若朝向相同,則 f[i] 取 1, 反之取0。每次反轉時,實際上只有第 i 只牛和第 i+k+1 只牛的相對位置變了,中間部分牛的相對狀態並沒有任何改變,在對第 i 只牛和第 i+k+1 只牛狀態實時更新後,再檢查餘下的牛是否朝向正確(驗證當前的k是否可行),最終可求得最少反轉次數。此種方法時間複雜度 O(N2)。

程式碼

#include <iostream>
#include <cstdio>

using namespace std;
const int max_n = 5005;
int f[max_n], dir[max_n], n;

int calc(int k){
    int res = 0;
    for(int i=1; i<=n-k+1; ++i){
        if(f[i]){
            ++res;
            f[i+k]^=1;
        }
    }
    for(int i=n-k+2; i<=n; ++i){
        if(f[i]){
            res = -1;
            break;
        }
    }
    return res;
}

int main()
{
    cin >> n;
    if(n<0) return 0;

    char s, base = 'F';
    for(int i=1; i<=n; ++i){
        cin >> s;
        if(s!=base){
            dir[i] = 1;
            base = s;
        }
        else dir[i] = 0;
    }

    int K = 1, M = n;

    for(int k=1; k<=n; ++k){
        memcpy(f, dir, sizeof(dir));
        int m = calc(k);
        if(m>=0 && M>m){
            K = k;
            M = m;
        }
    }
    cout << K << ' ' << M << endl;
    return 0;
}