[编程练习] POJ 3276 Face The Right Way

POJ 3276 Face The Right Way

  • Description
    • Input
    • Output
    • Sample Input
    • Sample Output
    • 思路
    • 代码

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 只牛的相对位置变了,中间部分牛的相对状态并没有任何改变,在对第 i 只牛和第 i+k 只牛状态实时更新后,再检查余下的牛是否朝向正确(验证当前的k是否可行),最终可求得最少反转次数。此种方法时间复杂度 O(N2)。

代码

#include 
#include 

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

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;
    }

    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;
}

你可能感兴趣的:(C++)