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

来源:互联网 发布:全球变暖 知乎 编辑:程序博客网 时间:2024/06/11 14:03

思路不是太难。每个串两种状态,翻转或者不翻转,从前一个状态转移到当前状态时,当前状态两种情况,前一个状态也是两种情况,公四种情况,扫一遍就好了。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;}
阅读全文
0 0
原创粉丝点击