題目大意:
給出一串由b,r,w組成的珠子,其中w可以當作b或r使用,可以從某一處斷開,然後向兩邊收集,只有同色才能收集,否則停止,求最多能收集的珠子數目
規模:
珠子串長度<=350
方法1:類比
枚舉斷開的位置,然後分別向兩邊開始收集珠子;
效率是O(N^2)
看了Analysis之後,學習了Dynamic Progamming的方法
方法2:
如果朝某一個方向開始搜集,能搜集到的珠子只和前面收集的相關,滿足了無後向性。
if color[i] = 'w' r[i] = r[i-1]+1</p><p> b[i] = b[i-1]+1</p><p> color[i] = 'r' r[i] = r[i-1]+1</p><p> b[i] = 0</p><p> color[i] = 'b' r[i] = 0</p><p> b[i] = b[i-1]+1</p><p>
分別預先處理出從左向後和從右向左兩個方向的情況,再枚舉間斷點就可以了
效率是O(N)
這道題目最大的啟發在於倍長字串來處理需要迴圈的問題
My Code:
#include <stdio.h><br />#include <string.h><br />int main(){<br />freopen("beads.in", "r", stdin);<br />freopen("beads.out", "w", stdout);<br />int n, color[1000];<br />memset(color, 0, sizeof(color));<br />scanf("%d", &n);<br />char c;<br />c = getchar();<br />int i, breakpoint;<br />for (i = 0; i < n; i++){<br />c = getchar();<br />if (c == 'b') color[i] = 1;<br />else if (c == 'r') color[i] = 2;<br />color[i+n] = color[i];<br />}<br />int max = 0;<br />for (breakpoint = 0; breakpoint < n; breakpoint++){<br />int left = breakpoint, right = breakpoint+1;<br />int now, collect = 0;<br />now = 0;<br />while (left >= 0){<br />if (now == 0) now = color[left];<br />if (now != color[left] && color[left] != 0) break;<br />collect++;<br />left--;<br />}<br />now = 0;<br />while (right < n+n){<br />if (now == 0) now = color[right];<br />if (now != color[right] && color[right] != 0) break;<br />collect++;<br />right++;<br />}<br />if (collect > max) max = collect;<br />}<br />if (max > n) max = n;<br />printf("%d/n", max);<br />return 0;<br />}