Files
problemas-para-competicao-p…/decode-ways/src/ac.cpp

56 lines
1.4 KiB
C++

#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
ll numDecodings(string s)
{
if (s[0] == '0')
return 0;
for (int i = 1; i < s.size(); i++)
{
if (s[i] == '0' && s[i - 1] == '0')
return 0;
}
// each letter can be a part of the message on their on
// they can extend the last letter to also form another part of the mesage
// let dp[i][{0, 1}] be the number of different messages ending at the i(th) char when the i(th) char
// is not concatenated with i-1(th) char or is.
// if s[i] is between 1 and 26 then it can be added alone, so dp[i][0] = dp[i - 1][0] + dp[i - 1][1]
// if s[i] concatenated with s[i - 1] and is between 1 and 26 then they can be added togheter, dp[i][1] = dp[i - 2][0] + dp[i - 2][1]
// dp[1][0] = 1, dp[1][1] = 0
int N = s.size();
vector<vector<ll>> dp(N + 1, vector<ll>(2, 0));
dp[1][0] = 1, dp[1][1] = 0;
dp[0][0] = 1;
for (int i = 2; i <= N; i++)
{
char current = s[i - 1], last = s[i - 2];
string aux = "";
aux += last;
aux += current;
if (current != '0')
{
dp[i][0] = dp[i - 1][0] + dp[i - 1][1];
}
int code = stoi(aux);
if (10 <= code && code <= 26)
{
dp[i][1] = dp[i - 2][0] + dp[i - 2][1];
}
}
return dp[N][0] + dp[N][1];
}
int main()
{
int n; cin >> n;
string code; cin >> code;
cout << numDecodings(code) << endl;
return 0;
}