首页 > 代码库 > CodeForces - 706C Hard problem(dp+字符串)

CodeForces - 706C Hard problem(dp+字符串)

题意:有n个字符串,只能将其逆转,不能交换位置,且已知逆转某字符串需要消耗的能量,问将这n个字符串按字典序从小到大排序所需消耗的最少能量。

分析:每个字符串要么逆转,要么不逆转,相邻两个字符串进行比较,从而可得4个状态转移方程。

#include<cstdio>#include<cstring>#include<cstdlib>#include<cctype>#include<cmath>#include<iostream>#include<sstream>#include<iterator>#include<algorithm>#include<string>#include<vector>#include<set>#include<map>#include<stack>#include<deque>#include<queue>#include<list>#define lowbit(x) (x & (-x))const double eps = 1e-8;inline int dcmp(double a, double b){    if(fabs(a - b) < eps) return 0;    return a > b ? 1 : -1;}typedef long long LL;typedef unsigned long long ULL;const int INT_INF = 0x3f3f3f3f;const int INT_M_INF = 0x7f7f7f7f;const LL LL_INF = 0x3f3f3f3f3f3f3f3f;const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f;const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};const int MOD = 1e9 + 7;const double pi = acos(-1.0);const int MAXN = 100000 + 10;const int MAXT = 10000 + 10;using namespace std;LL c[MAXN];string s[MAXN][2];LL dp[MAXN][2];int main(){    int n;    scanf("%d", &n);    for(int i = 0; i < n; ++i){        scanf("%I64d", &c[i]);    }    string tmp;    for(int i = 0; i < n; ++i){        cin >> tmp;        s[i][0] = tmp;        reverse(tmp.begin(), tmp.end());        s[i][1] = tmp;    }    memset(dp, LL_INF, sizeof dp);    dp[0][0] = 0, dp[0][1] = c[0];    bool ok = true;    for(int i = 1; i < n; ++i){        if(s[i][0] >= s[i - 1][0]){            dp[i][0] = min(dp[i][0], dp[i - 1][0]);        }        if(s[i][1] >= s[i - 1][0]){            dp[i][1] = min(dp[i][1], dp[i - 1][0] + c[i]);        }        if(s[i][0] >= s[i - 1][1]){            dp[i][0] = min(dp[i][0], dp[i - 1][1]);        }        if(s[i][1] >= s[i - 1][1]){            dp[i][1] = min(dp[i][1], dp[i - 1][1] + c[i]);        }        if(dp[i][0] == LL_INF && dp[i][1] == LL_INF){            ok = false;            break;        }    }    if(ok){        printf("%I64d\n", min(dp[n - 1][0], dp[n - 1][1]));    }    else{        printf("-1\n");    }    return 0;}

  

CodeForces - 706C Hard problem(dp+字符串)