USACO 1.1 broken necklace 分析

來源:互聯網
上載者:User

題目大意:

      給出一串由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 />}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.