標籤:string printf 數組 lower long 規劃 strong std ble
題目連結:http://codeforces.com/problemset/problem/706/C
題目大意: 給定n個字串, 每個字串可以顛倒前後位置(第一個字母到最後一個,第二個字母到倒數第二位) 每次顛倒需要花費ci的力氣, 要求將所給的n個字串用最小力氣按字典序排列, 輸出力氣值, 如果無法按字典序排列, 則輸出-1
資料範圍:2?≤?n?≤?100?000 、 ci (0?≤?ci?≤?1e9) 所有字串總長度不會超過1000000。
解題思路: 這是一道DP題, dp[i][0/1]分別表示第i個字串不動或者顛倒, 做DP題的時候一定要時時刻刻記住學長說的那句話 DP很智能,想多了就把自己繞進去了。
當時自己沒做出來 去百度了一下, 學到了直接用字串, 還有用 reverse(b[i].begin(),b[i].end()); 可以直接將區間內倒序。
這道題有幾個坑點: 一 dp數組要開long long 、二 平時經常用const int MaxN = 1<<30 ; 做這道題想都沒想就寫上去了 結果wrong了一發, 後來才發現開一個long long類型的來比較 一般開到1e15比較保險;其他的都是普通dp套路。
代碼如下:
1 #include<cstdio> 2 #include<cstring> 3 #include<cmath> 4 #include<cstdlib> 5 #include<algorithm> 6 #include<iostream> 7 using namespace std; 8 typedef long long LL; 9 const int MaxN = 1e5;10 const LL inf = 1e15;11 int n;12 LL num[MaxN + 5];13 LL dp[MaxN + 5][2];14 string a[MaxN + 5], b[MaxN + 5];15 int len;16 int main()17 {18 scanf("%d", &n);19 for(int i = 1; i <= n; i++)20 scanf("%I64d", &num[i]);21 for(int i = 1; i <= n; i++){22 cin >> a[i];23 b[i]=a[i];24 reverse(b[i].begin(),b[i].end());25 }26 for(int i = 1; i <= n; i++)27 dp[i][0] = dp[i][1] = inf;28 dp[1][0] = 0;29 dp[1][1] = num[1];30 int i;31 for(i = 2; i <= n; i++){32 if(a[i] >= a[i - 1])33 dp[i][0] = dp[i - 1][0];34 if(b[i] >= a[i - 1])35 dp[i][1] = dp[i - 1][0] + num[i];36 if(a[i] >= b[i - 1])37 dp[i][0] = min(dp[i][0], dp[i - 1][1]);38 if(b[i] >= b[i - 1])39 dp[i][1] = min(dp[i][1], dp[i - 1][1] + num[i]);40 if(dp[i][0] == inf && dp[i][1] == inf)41 break;42 }43 if(i == n + 1)44 printf("%I64d\n", min(dp[n][1], dp[n][0]));45 else46 printf("-1\n");47 return 0;48 }
codeforces 706C Hard problem DP(動態規劃)問題