I am currently trying out a programming problem, SPOJ Alphacode, that involves dynamic programming. In an encoding system where A=1, B=2, …, Z=26, a message 25114
is ambiguous, and could be decoded in 6 ways (BEAN
, BEAAD
, YAAD
, YAN
, YKD
, or BEKD
). The challenge is to count the number of ways each given input number can be decoded.
Since, this is my second DP problem I am trying out, my code doesn't seem to be optimised, resulting in a time limit exceed error.
Although I have noticed that I have used a lot of for loops, I am not sure how to get rid of them.
Can someone please help me optimise this code? And also, can someone tell me tips on how to optimise codes so that in the future, I can fix Time Limit Exceeded errors by myself?
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<string> input;
int addProc(string a, string b)
{
int n = stoi(a) * 10 + stoi(b);
if(n > 26)
{
return 0;
}
else
{
return n;
}
}
int dp(int i)
{
vector<vector<string> > comb(1);
comb[0].push_back(string(1, input[i].at(0)));
for(int j = 1; j < input[i].length(); j++)
{
int l = comb.size();
for(int k = 0; k < l; k++)
{
if(comb[k][comb[k].size() - 1] != "0")
{
if(input[i].at(j) == '0')
{
int n = addProc(comb[k][comb[k].size() - 1], "0");
comb[k].push_back(to_string(n));
}
else
{
comb[k].push_back(string(1, input[i].at(j)));
int n = addProc(comb[k][comb[k].size() - 2], string(1, input[i].at(j)));
vector<string> temp(comb[k].begin(), comb[k].end() - 1);
temp[temp.size() - 1] = to_string(n);
comb.push_back(temp);
}
}
}
}
int count = 0;
for(int j = 0; j < comb.size(); j++)
{
if(comb[j][comb[j].size() - 1] != "0")
{
count++;
}
}
return count;
}
int main()
{
ios_base::sync_with_stdio(false);
string a = "";
while(true)
{
cin >> a;
if(a != "0")
{
input.push_back(a);
}
else
{
break;
}
}
for(int i = 0; i < input.size(); i++)
{
cout << dp(i) << "\n";
}
return 0;
}
comb
array? I can tell by your final counting loop that you are doing it wrong because that loop appears to take \$O(n^2)\$ time. But I only skimmed your code so I may be wrong. \$\endgroup\$