706C - Hard problem - CodeForces Solution


dp strings *1600

Please click on ads to support us..

Python Code:

n = int(input())
c = [int(x) for x in input().split()]
s = []
for i in range(n):
    s.append(input())
v = 0
w = c[0]
inf = 10**16
new,newr = s[0],s[0][::-1]
for i in range(1,n):
    last,lastr = new,newr
    new,newr = s[i],s[i][::-1]
    V = [inf]
    if last <=new: V.append(v)
    if lastr<=new: V.append(w)
    W = [inf]
    if last <=newr: W.append(v)
    if lastr<=newr: W.append(w)
    v,w = min(V), min(W)+c[i]
score = min(v,w)
print(score if score<inf else -1)

C++ Code:

#include <bits/stdc++.h>
using namespace std;

#define int long long
const int INF = 1e18;
const int N = 2e5 + 5;
const int M = 1e9 + 7;

signed main()
{
    ios_base::sync_with_stdio(0),
        cin.tie(0);

    int n;
    cin >> n;
    vector<string> v(n + 2);
    int c[n + 2], dp[n + 2][2];

    for (int i = 1; i <= n; i++)
        cin >> c[i];

    for (int i = 1; i <= n; i++)
        cin >> v[i];

    dp[1][0] = 0;
    dp[1][1] = c[1];

    for (int i = 2; i <= n; i++)
    {
        dp[i][0] = dp[i][1] = INF;

        if (dp[i - 1][0] != INF)
        {

            if (v[i] >= v[i - 1])
                dp[i][0] = dp[i - 1][0];
            string rev = v[i];
            reverse(rev.begin(), rev.end());
            if (rev >= v[i - 1])
                dp[i][1] = dp[i - 1][0] + c[i];
        }

        if (dp[i - 1][1] != INF)
        {

            string rev = v[i - 1];
            reverse(rev.begin(), rev.end());
            if (v[i] >= rev)
                dp[i][0] = min(dp[i][0], dp[i - 1][1]);

            string rev2 = v[i];
            reverse(rev2.begin(), rev2.end());
            if (rev2 >= rev)
                dp[i][1] = min(dp[i][1], dp[i - 1][1] + c[i]);
        }
    }

    int ans = min(dp[n][0], dp[n][1]);
    if (ans == INF)
        cout << "-1";
    else
        cout << ans;
}


Comments

Submit
0 Comments
More Questions

742A - Arpa’s hard exam and Mehrdad’s naive cheat
1492A - Three swimmers
1360E - Polygon
1517D - Explorer Space
1230B - Ania and Minimizing
1201A - Important Exam
676A - Nicholas and Permutation
431A - Black Square
474B - Worms
987B - High School Become Human
1223A - CME
1658B - Marin and Anti-coprime Permutation
14B - Young Photographer
143A - Help Vasilisa the Wise 2
320A - Magic Numbers
1658A - Marin and Photoshoot
514A - Chewbaсca and Number
382A - Ksenia and Pan Scales
734B - Anton and Digits
1080A - Petya and Origami
1642D - Repetitions Decoding
1440A - Buy the String
1658F - Juju and Binary String
478A - Initial Bet
981A - Antipalindrome
365A - Good Number
1204B - Mislove Has Lost an Array
1409D - Decrease the Sum of Digits
1476E - Pattern Matching
1107A - Digits Sequence Dividing