Printing Longest Common Substring algorithm

#include <bits/stdc++.h> 
using namespace std; 
int main(){
     string s,x;
     cin>>s;
     cin>>x;
     int a=s.length();
int b=x.length();
string dp[a+1][b+1];
for (int i=0;i<=a;i++){
	for(int j=0;j<=b;j++){
		if (i==0 || j==0){
			dp[i][j]="";
		}
		else if(s[i-1]==x[j-1]){
			dp[i][j]=dp[i-1][j-1]+s[i-1];
			
		}
		else{
			if(i>j){
				dp[i][j]=dp[i-1][j];
			}
			else{
				dp[i][j]=dp[i][j-1];
			}
		}
	}
}
cout<<dp[a][b];
}

This code is similar to finding the length of the longest common substring the only difference is that in the array dp it records the longest substring using i chars from the first string and j chars from the second. This algorithm has a complexity of O(a*b) where a,b are the lengths of the first string and second string respectively. I don’t think there is an algorithm with better time complexity, I still get TLE error. The constraints are that the lengths must be less than 3000 and the max time is 2 secs for 18 test cases. Why is this program slow, and how can i optimize this.