NC25065. [USACO 2007 Mar G]Face The Right Way
描述
输入描述
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; }