poj3276(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
Lines 2.. N+1: Line i+1 contains a single character, F&nbs***bsp; B, indicating whether cow i is facing forward or backward.
Output
Sample Input
7 B B F B F B B
Sample Output
3 3
Hint
首先枚举k,对于一个特定的k,最左端只有一个区间能够影响得到,所以可以确定是否反转。然后这个端点就不会再被影响,这样长度就减1了,重复以上步骤就能得出答案。还运用到了一个小技巧,用f[i]来记录i是否被反转,这样就不需要真正的实现反转,时间复杂度降低。
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <map>
#include <vector>
#include <list>
#include <set>
#include <stack>
#include <queue>
#include <deque>
#include <algorithm>
#include <functional>
#include <iomanip>
#include <limits>
#include <new>
#include <utility>
#include <iterator>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <ctime>
using namespace std;
int n;
int dir[5010];//牛的方向(0:F, 1:B)
int f[5010];//区间[i, i+k-1]是否被反转
int calc(int k)
{
memset(f, 0, sizeof(f));
int res = 0, sum = 0;
for (int i = 0; i + k <= n; ++i)
{
if ((dir[i]+sum)&1)
{
res++;
f[i] = 1;
}
sum += f[i];
if (i - k + 1 >= 0)
sum -= f[i-k+1];
}
for (int i = n-k+1; i < n; ++i)
{
if ((dir[i]+sum)&1)
return -1;
if (i - k + 1 >= 0)
sum -= f[i-k+1];
}
return res;
}
int main()
{
cin >> n;
char s[5];
for (int i = 0; i < n; ++i)
{
scanf("%s", s);
dir[i] = (s[0] == 'B');
}
int K = 1, M = n;
for (int k = 1; k <= n; ++k)
{
int m = calc(k);
if (m >= 0 && m < M)
{
M = m;
K = k;
}
}
cout << K << ' ' << M << endl;
return 0;
}
公众号「算法码上来」。godweiyang带你学习算法,不管是编程算法,还是深度学习、自然语言处理算法都一网打尽,更有各种计算机新鲜知识和你分享。别急,算法码上来。