I have written code for https://www.spoj.com/problems/AIBOHP/16 in both python and c++. Both the solutions follow the exact logic. While c++ gets AC, python gets TLE. It would be very helpful if someone could come forward and explain the difference in the code. This is very crucial because I would have to switch to C++ completely if python has this disadvantage.
Python Solution:
if __name__ == '__main__':
import sys
from sys import stdin, stdout
sys.setrecursionlimit(3*6111)
def solve(i, j):
if i>=j:
return 0
if T[i][j]!=-1:
return T[i][j]
if s[i]==s[j]:
T[i][j] = solve(i+1, j-1)
else:
T[i][j] = 1 + min(solve(i+1, j), solve(i,j-1))
return T[i][j]
t = int(stdin.readline())
for _ in range(t):
s = stdin.readline()[:-1]
n = len(s)
T = [[-1 for _ in range(n+1)]for _ in range(n+1)]
stdout.write(str(solve(0, n-1)) + '\n')
C++ solution:
#include <iostream>
#include<string.h>
using namespace std;
long T[6110][6110];
string str;
long solve(long i,long j)
{
if(i >= j)
return 0;
if(T[i][j] != -1)
return T[i][j];
if(str[i] == str[j])
{
T[i][j] = solve(i+1,j-1);
}
else
T[i][j] = 1 + min(solve(i+1,j),solve(i,j-1));
return T[i][j];
}
int main() {
long t,n,m;
cin>>t;
cin.ignore();
while(t--)
{
getline(cin,str);
memset(T,-1,sizeof(T));
cout<<solve(0,str.length()-1)<<"\n";
}
return 0;
}
Thank you for your time and consideration!
created
last reply
- 7
replies
- 1.2k
views
- 3
users
- 1
like
- 3
links