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 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~