ACM题目————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 or 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
题目大概意思就是说:n头牛,两个方向,向后B,向前F,每次转K头牛,最少转cnt次,
最终使所有的牛向前。求最少的K以及对应的cnt。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | #include <stdio.h> #include <string.h> #define maxn 5010 int cow[maxn], N, K, M; // 奶牛们的初始位置,0前1后 int tra[maxn]; // 是否翻转第i头牛,1翻 int cal( int k) // 翻转顺序从左往右 { int ans = 0, i, sum = 0; for (i = 0; i + k <= N; ++i) { tra[i] = 0; if ((sum + cow[i]) & 1) { tra[i] = 1; ++ans; } sum += tra[i]; // 尺取法 if (i - k + 1 >= 0) sum -= tra[i-k+1]; } // 检查剩下的是否有反向奶牛 for ( ; i < N; ++i) if ((sum + cow[i]) & 1) return -1; else if (i - k + 1 >= 0) sum -= tra[i-k+1]; return ans; } int main() { char ch[2]; int i, m, k; scanf ( "%d" , &N); for (i = 0; i < N; ++i) { scanf ( "%s" , ch); if (ch[0] == 'B' ) cow[i] = 1; else cow[i] = 0; } M = N; K = 1; for (k = 1; k <= N; ++k) { m = cal(k); if (m >= 0 && m < M) { M = m; K = k; } } printf ( "%d %d\n" , K, M); return 0; } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理