列表

详情


NC25065. [USACO 2007 Mar G]Face The Right Way

描述

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.

输入描述

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.

输出描述

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

示例1

输入:

7
B
B
F
B
F
B
B

输出:

3 3

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++11(clang++ 3.9) 解法, 执行用时: 47ms, 内存消耗: 480K, 提交时间: 2019-06-21 23:18:11

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn = 5e3 + 5;
const int INF = 1 << 30;
int book[maxn], temp[maxn], n, ansnum, ansk;
char pre, now;
int main()
{
    while(~scanf("%d", &n))
    {
        pre = 'F';
        for(int i = 1; i <= n; i++)  //这种方式可能想不到的。。。
        {
            scanf(" %c", &now);
            if(pre == now)
                book[i] = 0;
            else
                book[i] = 1;
            pre = now;
        }
        ansnum = INF;
        for(int k = 1; k <= n; k++)
        {
            memcpy(temp, book, sizeof(book)); //memcpy对int类型也可以用
            int cnt = 0, flag = 0;
            for(int i = 1; i <= n-k+1; i++)
            {
                if(temp[i])
                    cnt++, temp[i+k] ^= 1;  //这样子就相当于反转了
            }
            for(int i = n-k+2; i <= n; i++)  //如果n-k+2里面,如果有朝后的就没有办法再有办法转动了。。。因为前面的保证了前面的都是往前的,这里没法转了
            {
                if(temp[i])
                {
                    flag = 1;
                    break;
                }
            }
            if(!flag)
            {
                if(ansnum > cnt)
                {
                    ansnum = cnt;
                    ansk = k;
                }
            }
        }
 
        printf("%d %d\n", ansk, ansnum);
    }
    return 0;
}

上一题