您的位置:首页 > 其它

POJ 3276 (水题)

2016-02-17 14:31 351 查看
Face The Right Way

Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 3618 Accepted: 1669
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

Hint

For K = 3, the machine must be operated three times: turn cows (1,2,3), (3,4,5), and finally (5,6,7)
Source

USACO 2007 March Gold
题意是给出n头牛的状态,确定一个操作长度使得能够得到最小的操作次数(当操作次数相同取最小的操作长度),操作就是把某一段长度的牛全部翻转方向,最终都变成F。

如果用g[i]表示第i次操作有没有翻转,那么g[i-k+1]+g[i-k+2]+...+g[i]模2就是i位置最终有没有翻转。

#include <iostream>
#include <cmath>
#include <cstdlib>
#include <time.h>
#include <vector>
#include <cstdio>
#include <cstring>
#include <map>
#include <algorithm>
using namespace std;
#define maxn 51111

char a[maxn];
int f[maxn], g[maxn];
int n;

int ok (int k) {
memset (g, 0, sizeof g);
for (int i = 1; i <= n; i++) {
f[i] = (a[i] == 'B');
}
int cnt = 0, sum = 0;
for (int i = 1; i <= n-k+1; i++) {
if (i > k) {
sum -= g[i-k];
}
if (sum%2 != f[i]) {
cnt++;
sum++;
g[i] = 1;
}
}
for (int i = n-k+2; i <= n; i++) {
sum -= g[i-k];
if (sum%2 != f[i])
return 11111111;
}
return cnt;
}

int main () {
while (scanf ("%d", &n) == 1) {
getchar ();
for (int i = 1; i <= n; i++) {
a[i] = getchar ();
getchar ();
}
int ans = 11111111, len;
for (int i = 1; i <= n; i++) {
int cur = ok (i);
if (cur < ans) {
ans = cur;
len = i;
}
}
printf ("%d %d\n", len, ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: