1. 程式人生 > >CodeForces 706 C. Hard problem(dp)

CodeForces 706 C. Hard problem(dp)

Description
給出n個字串,翻轉第i個串需要一個代價c[i],問使得這n個字串保持升序所需的最小代價
Input
第一行一整數n表示字串數量,之後n個整數c[i]表示翻轉第i個串所需花費,最後n個字串,總串長100000
(2<=n<=100000,0<=c[i]<=1e9)
Output
輸出使得這n個串保持升序的最小代價
Sample Input
2
1 2
ba
ac
Sample Output
1
Solution
dp[i][0]和dp[i][1]表示不翻轉和翻轉第i個串使得前i個串保持升序的最小代價,每次列舉幾種使得s[i]>=s[i-1]的方案進行轉移即可
Code

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
#define INF 1e14+5
#define maxn 111111
string s[maxn],ss[maxn]; int n,c[maxn]; ll dp[maxn][2]; string deal(string a) { string ans=a; int len=a.length(); for(int i=0,j=len-1;i<j;i++,j--)swap(a[i],a[j]); return a; } int main() { while(~scanf("%d",&n)) { for(int i=1;i<=n;i++)cin>>c[i]; for
(int i=1;i<=n;i++)cin>>s[i],ss[i]=deal(s[i]); for(int i=1;i<=n;i++)dp[i][0]=dp[i][1]=INF; //printf("%I64d\n",dp[1][1]); dp[1][0]=0,dp[1][1]=c[1]; int flag=1; for(int i=2;i<=n;i++) { if(s[i]>=s[i-1])dp[i][0]=min(dp[i][0],dp[i-1][0]); if(s[i]>=ss[i-1])dp[i][0]=min(dp[i][0],dp[i-1][1]); if(ss[i]>=s[i-1])dp[i][1]=min(dp[i][1],dp[i-1][0]+c[i]); if(ss[i]>=ss[i-1])dp[i][1]=min(dp[i][1],dp[i-1][1]+c[i]); if(dp[i][0]==INF&&dp[i][1]==INF) { flag=0; break; } } if(flag)printf("%I64d\n",min(dp[n][0],dp[n][1])); else printf("-1\n"); } return 0; }