HDU 4960 Another OCD Patient 簡單DP

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   for   ar   

思路:

  因為是對稱的,所以如果兩段是對稱的,那麼一段的首碼和一定等於另一段的尾碼和。根據這個性質,我們可以預先處理出這個數列的對稱點對。然後最後一個對稱段是從哪裡開始的,做n^2的DP就可以了。

 

代碼:

  

 1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include <cmath> 6 #include <algorithm> 7 #include <string> 8 #include <queue> 9 #include <stack>10 #include <vector>11 #include <map>12 #include <set>13 #include <functional>14 #include <cctype>15 #include <time.h>16 17 using namespace std;18 19 typedef __int64 ll;20 21 const int INF = 1<<30;22 const int MAXN = (int) 5055;23 24 inline void nextInt(int &x) {25     char c = getchar();26     x = 0;27     while (isdigit(c)) {28         x = x*10 + c-‘0‘;29         c = getchar();30     }31 }32 33 inline void nextLL(ll &x) {34     char c = getchar();35     x = 0;36     while (isdigit(c)) {37         x = x*10 + c-‘0‘;38         c = getchar();39     }40 }41 42 ll a[MAXN], V[MAXN], prefix[MAXN], suffix[MAXN];43 ll dp[MAXN];44 int sym[MAXN];45 int n;46 47 void solve() {48     a[0] = 0;49     prefix[0] = suffix[n+1] = 0;50     for (int i = 1; i <= n; i++) prefix[i] = suffix[i] = V[i];51     for (int i = 0; i < n; i++) prefix[i+1] += prefix[i]; //首碼和52     for (int i = n; i > 0; i--) suffix[i] += suffix[i+1]; //尾碼和53 54     for (int i = 1, j = n; i <= n; i++) { //求對稱點55         sym[i] = -1;56         while (j>0 && prefix[i]>suffix[j]) j--;57         if (prefix[i]==suffix[j]) sym[i] = j;58     }59 60     memset(dp, -1, sizeof(dp));61     for (int i = 1; i <= n; i++) if (sym[i]>0) { //這一點有對稱點62         if (sym[i] <= i) break; //枚舉過界63         dp[i] = a[i] + a[n-sym[i]+1]; //前面是一整段64         for (int j = 1; j < i; j++) if (sym[j]>0) { //從j轉移過來65             dp[i] = min(dp[i], dp[j]+a[i-j]+a[sym[j]-sym[i]]);66         }67     }68 69     ll ans = a[n];70     for (int i = 1; i <= n; i++) if (dp[i]>=0)71         ans = min(ans, dp[i]+a[sym[i]-i-1]); //中間合成一段72     printf("%I64d\n", ans);73 }74 75 int main() {76     #ifdef Phantom0177         freopen("HDU4960.txt", "r", stdin);78     #endif //Phantom0179 80     while (1) {81         nextInt(n);82         if (n==0) break;83         for (int i = 1; i <= n; i++)84             nextLL(V[i]);85         for (int i = 1; i <= n; i++)86             nextLL(a[i]);87         solve();88     }89 90     return 0;91 }
View Code

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.