天天看點

Codeforces Round #367 (Div. 2) C Hard problem (dp)

思路不是太難。每個串兩種狀态,翻轉或者不翻轉,從前一個狀态轉移到目前狀态時,目前狀态兩種情況,前一個狀态也是兩種情況,公四種情況,掃一遍就好了。dp[i][0]表示第i個串不翻轉,dp[i][1]表示第i個串翻轉。

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MAXN = 1e5+10;
const LL INF = 1LL<<62;
string strs[MAXN][2];
LL weight[MAXN];
LL dp[MAXN][2];

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n;
    cin >> n;
    dp[n][0] = dp[n][1] = INF;
    for(int i = 0; i < n; ++i)
    {
        cin >> weight[i];
        dp[i][0] = dp[i][1] = INF;
    }
    for(int i = 0; i < n; ++i)
    {
        cin >> strs[i][0];
        strs[i][1] = string(strs[i][0].rbegin(),strs[i][0].rend());
    }
    dp[0][0] = 0;
    dp[0][1] = weight[0];
    for(int i = 1; i < n; ++i)
    {
        if(strs[i][0] >= strs[i-1][0])
        {
            dp[i][0] = min(dp[i][0],dp[i-1][0]);
        }
        if(strs[i][0] >= strs[i-1][1])
        {
            dp[i][0] = min(dp[i][0],dp[i-1][1]);
        }
        if(strs[i][1] >= strs[i-1][0])
        {
            dp[i][1] = min(dp[i][1],dp[i-1][0] + weight[i]);
        }
        if(strs[i][1] >= strs[i-1][1])
        {
            dp[i][1] = min(dp[i][1],dp[i-1][1] + weight[i]);
        }
    }
    LL res = min(dp[n-1][0],dp[n-1][1]);
    if(res == INF)
        cout << -1 << endl;
    else
        cout << res << endl;
    return 0;
}