Top down approach of longest increasing subsequence? - c++

https://leetcode.com/problems/longest-increasing-subsequence/
This the link of the question which I tried to solve using recursion + memorization technique but not able to solve my testcases only pass only up to 4 is also I don't know that whether my approach is correct or not.
Below this line is the code I tried:
int lis( vector<int>& nums, int i, int n, int prev, vector<int>& ls){
if(i==n||n==0){
return 0;
}
if(ls[i]!=-1){
return 1 ;
}
lis(nums,i+1,n,prev,ls);
if(nums[i]>prev){
int num=1+lis(nums,i+1,n,nums[i],ls);
ls[num]=1;
return num;
}
return 0;
}
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int n=nums.size();
int c;
vector<int> ls(n+1,-1);
lis(nums,0,n,INT_MIN,ls);
for(int i=n;i>=0;i--) {
if(ls[i]!=-1) {
c=i;
break;
}
else {
c=0;
}
}
if(nums.size()==0) {
return 0;
}
else {
if(c==0) {
return 0;
}
else {
return c;
}
}
}
};
I want to know how to apply recursion + memorization technique in this type of question. Everyone is teaching bottom up approach, not top down approach so it is hard to understand top down. So explain me how to solve this question?

Related

I have written a C++ program to solve sudoku puzzle ,it is showing "Exception has occurred. EXC_BAD_ACCESS"

Here is the code I have written:
#include<iostream>
using namespace std;
int puzzle[9][9]=
{
{0,5,0,0,6,2,7,0,0},
{0,0,0,0,0,0,1,0,2},
{7,0,9,3,0,0,0,0,0},
{3,0,0,0,8,0,0,0,0},
{0,8,0,7,0,9,0,2,0},
{0,0,0,0,5,0,0,0,7},
{0,0,0,0,0,6,2,0,8},
{2,0,6,0,0,0,0,0,0},
{0,0,3,4,2,0,0,9,0},
};//puzzle template
bool row_possible(int row,int number);//To find out whether a number is possible in the particular row
bool column_possible(int column,int number);//To find whether a number is possible in the particular column
bool square_possible(int row,int column,int number);//To find whether a number is possible in its square
bool possible(int row,int column,int number);//To find whether a number is possible in the given position
bool unassigned();//To check whether the puzzle has any unassigned spaces
void printSolution();//To print the final solution to the console
bool solve();//To solve the puzzle
int main()
{
if(solve())
printSolution();
else
cout<<"\nNo Solution";
return 0;
}
bool row_possible(int row,int number)
{
int m=0;
for(int column=0;column<9;column++)
{
if(puzzle[row-1][column]==number)
m++;
}
if(m!=0)
return false;
else
{
return true;
}
}
bool column_possible(int column,int number)
{
int m=0;
for(int row=0;row<9;row++)
{
if(puzzle[row][column-1]==number)
m++;
}
if (m!=0)
return false;
else
{
return true;
}
}
bool square_possible(int row,int column,int number)
{
int mod_x=(row-1)%3,mod_y=(column-1)%3;
int i=(row-1)-mod_x,j=(column-1)-mod_y;
int m=0;
int k=0;
int check_x=3,check_y=3;
for(k=0;check_x!=0;check_x--)
{
for(k=0;check_y!=0;check_y--)
{
if(puzzle[i][j]==number)
m++;
j++;
}
i++;
}
if(m!=0)
return false;
else
{
return true;
}
}
bool possible(int row,int column,int number)
{
if(row_possible(row,number)&&column_possible(column,number)&&square_possible(row,column,number))
return true;
else
{
return false;
}
}
bool unassigned()
{
int m=0;
for(int row=0;row<9;row++)
{
for(int column=0;column<9;column++)
{
if(puzzle[row][column]==0)
m++;
}
}
if(m>0)
return true;
else
{
return false;
}
}
void printSolution()
{
for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
{
cout<<puzzle[i][j]<<" ";
}
cout<<"\n";
}
}
bool solve()
{
if(!unassigned())
return true;
for(int row=1;row<10;row++)
{
for(int column=1;column<10;column++)
{
for(int number=1;number<10;number++)
{
if(possible(row,column,number))
{
puzzle[row-1][column-1]=number;
if(solve())
return true;
puzzle[row-1][column-1]=0;
}
}
}
}
return false;
}
The debugger is throwing the error in:
int m=0;
int k=0;
int check_x=3,check_y=3;
It says Exception has occurred.
EXC_BAD_ACCESS.It also says that read memory is failed.
I dont understand what it says.Let me also know whether my program needs any improvements
Kindly help me.I am using Visual Studio Code on MacOS.Thank You
You can do a simple calculation on how long it would take for you to get an answer.
You have 55 open cells that you try 9 different numbers. This gives you 955 = 3 * 1052 tries.
If one try takes 1μs it will take ~ 9.6 * 1038 years to find a solution.
I have written a C++ program and that finds a solution of this sudoku in 30ms and my PC is not a very fast one (5 years old) and 10ms of this is used to print the solution to screen with printf

C++ recursive solution of NQUEENS problem not working properly

I am trying to solve the famous NQUEENS problem using backtracking in c++ using vectors and class. But it is giving correct result for some cases(for ex. 5) and for remaining(for ex. 4) it is showing "Solutuon doesn't exist".
My code is as follows:
Class declaration for storing rows and columns of queen position.
class position
{
public:
int r,c;
position(int r,int c)
{
this->r=r;
this->c=c;
}
};
The recursive function:
vector<position> positions;
bool solve(int n, int r)
{
if(r==n)
return true;
for (int c = 0; c < n; ++c)
{
bool safe=true;
for(int q=0;q<r;++q)
{
if (positions[q].c == c || positions[q].r - positions[q].c == r - c
|| positions[q].r + positions[q].c == r + c)
{
safe = false;
break;
}
}
if(safe)
{
position p(r,c);
positions.push_back(p);
if(solve(n,r+1))
return true;
}
}
return false;
}
and the driver function is as follows:
int main()
{
int n;
cin>>n;
if(!solve(n,0))
{
cout<<"Solution doesn't exist"<<endl;
return 0;
}
printboard(n);
return 0;
}
Please help me in resolving this.
if(solve(n,r+1))
return true;
else
positions.erase(positions.begin()+positions.size()-1);
If the solution for one cell doesn't exist then erase that cell from possible positions so that it avoids collisions.
Edit:-
Thank You Mr.Bo R for your correction.

TLE in codeforces's Dijkstra

I just learnt Dijkstra's algorithm and solved a few problems and I am trying to solve this http://codeforces.com/problemset/problem/20/C problem but I am getting Time limit Exceeded in a large test case, I want to know if my code can be further optimized in any way or if there is any other faster implementation of Dijkstra then let me know.
My code
#include<bits/stdc++.h>
using namespace std;
#define pii pair<int,int>
#define vp vector<pii>
int p[100010],d[100010];
void printer(int current)
{
if(p[current]==-2)
{
printf("%d ",current);
return;
}
printer(p[current]);
printf("%d ",current);
}
class Prioritize
{
public:
int operator()(const pii &p1,const pii &p2)
{
return p1.second<p2.second;
}
};
int main()
{
priority_queue<pii, vp, Prioritize> Q;
int nv;
scanf("%d",&nv);
vp g[nv+1];
int ne,u,v,w;
scanf("%d",&ne);
for(int i=0;i<ne;i++)
{
scanf("%d %d %d",&u,&v,&w);
g[u].push_back(pii(v,w));
g[v].push_back(pii(u,w));
}
int source=1;
int size;
for(int i=1;i<=nv;i++)
{
d[i]=INT_MAX;
p[i]=-1;
}
d[source]=0;
p[source]=-2;//marker for source.
Q.push(pii(source,d[source]));
while(!Q.empty())
{
u=Q.top().first;
Q.pop();
size=g[u].size();
for(int i=0;i<size;i++)
{
v=g[u][i].first;
w=g[u][i].second;
if(d[v]>d[u]+w)
{
d[v]=d[u]+w;
p[v]=u;
Q.push(pii(v,d[v]));
}
}
}
/*for(int i=1;i<=nv;i++)
{
printf("Node %d and min weight = %d and parent = %d\n",i,d[i],p[i]);
}*/
if(p[nv]==-1)
{
printf("%d\n",-1);
return 0;
}
printer(nv);
return 0;
}
Your algorithm has complexity O(nm). I propose to add the following
Q.push(pii(source,d[source]));
while(!Q.empty())
{
u=Q.top().first;
int curD = Q.top().second; //this
if( curD > d[u]) continue; //and this
Q.pop();
size=g[u].size();
for(int i=0;i<size;i++)
{
After changes complexity will be O(mlogn). If you now russian you can read http://e-maxx.ru/algo/dijkstra_sparse

How to proceed further in this 8 queen algorithm?

The code and output is working fine before backtracking but I am not able to proceed for backtracking. What to do do after unplacing? It is giving the output of first 4 queens only means before backtracking.
#include <iostream>
#include <conio.h>
using namespace std;
int recu(int i,int k);
void place(int i,int k);
void unplace(int i,int k);
int q[8][8];
int row[8];
int column[8];
int c[15];
int d[15];
int totalqueens=0;
int s;
int main()
{
for(int i=0;i<8;i++) //Flags for rows,columns and diagonals
{
row[i]=0;
column[i]=0;
c[i]=0;d[i]=0;
}
for(int i=8;i<15;i++)
{
c[i]=0;d[i]=0;
}
int i=0;
int k=0;
recu(i,k);
for(int i=0;i<8;i++)
{
for(int k=0;k<8;k++)
{
if(q[i][k]==1)
{
cout<<"(";
cout<<i;
cout<<",";
cout<<k;
cout<<")";
}
}
}
getch();
return 0;
}
int recu(int i,int k)
{
if(totalqueens==8)
{ goto print; }
if(k<8)
{
if(column[i]==0 && row[k]==0 && c[i+k]==0 && d[i-k+7]==0)
{
place(i,k);
s=k;
k=0;
recu(i+1,k);
}
else
{
recu(i,k+1);
unplace(i-1,s);
//**I am not able to proceed further**
}
}
print:
;
}
void place(int i,int k)
{
totalqueens++;
q[i][k]=1;
row[k]=1;
column[i]=1;
c[i+k]=1;
d[i-k+7]=1;
}
void unplace(int i,int k)
{
q[i][k]=0;
row[i]=0;
column[k]=0;
c[i+k]=0;
d[i-k+7]=0;
//cout<<"before call";
recu(i,k+1);
//cout<<"working";
}
Your code only gives out one solution.
u r not put the output part in the right place.
try like this:
void print()
{
for(int i=0;i<8;i++)
{
for(int k=0;k<8;k++)
{
if(q[i][k]==1)
{
cout<<"(";
cout<<i;
cout<<",";
cout<<k;
cout<<")";
}
}
}
}
make that to be one method. and then, in your recu method, modify to:
if(totalqueens==8)
{
print();
return;
}
Keep in mind that DO NOT use goto sentence. It is very ugly and may cause unknown problems.
You backtrack when not all queens have been placed and you cannot place another queen. You backtrack as follows:
See if the last placed queen can be placed in a later spot. If so, place it there and stop backtracking. (Resume placing.)
Remove the last placed queen.
If there are no queens left, stop. All solutions have been found.
Go to step 1.

Segment Tree with lazy propagation Time limit problem

The following is the implementation of http://www.spoj.pl/problems/LITE/ using Segment Tree's with lazy propagation. I am new to segment trees and I cannot understand why I am getting TLE. Could someone please look at it and help me correct my error?
#include <iostream>
#include <iostream>
#include <cstdio>
#include <cstring>
#define MAX 100000
using namespace std;
int M[2*MAX+1];
int flag[2*MAX+1];
int count;
void refresh(int begin,int end,int n)
{
M[n] = end-begin+1 - M[n];
flag[n]=0;
flag[n*2] =!flag[n*2];
flag[n*2+1] =!flag[n*2+1];
}
void update(int begin,int end,int i,int j,int n=1)
{
if(flag[n])
{
refresh(begin,end,n);
}
if(begin>=i && end<=j)
{
if(!flag[n])
{
refresh(begin,end,n);
}
flag[n] = 0;
return;
}
else if(begin>=end)
{
return;
}
else
{
int mid = (begin+end)>>1;
if(i<=mid)
{
update(begin,mid,i,j,n*2);
}
if(j>mid)
{
update(mid+1,end,i,j,n*2+1);
}
if(flag[2*n])
{
refresh(begin,mid,2*n);
}
if(flag[2*n+1])
{
refresh(mid+1,end,2*n+1);
}
M[n] = M[n*2]+ M[n*2+1];
}
}
int query(int begin,int end,int i,int j,int n=1)
{
if(flag[n])
{
refresh(begin,end,n);
}
if(begin>=i && end<=j)
{
return M[n];
}
if(begin>=end)
{
return 0;
}
int mid = (begin+end)>>1;
int l=0,r=0;
if(i<=mid)
{
l = query(begin,mid,i,j,n*2);
}
if(j>mid)
{
r = query(mid+1,end,i,j,n*2+1);
}
if(flag[2*n])
{
refresh(begin,mid,2*n);
}
if(flag[2*n+1])
{
refresh(mid+1,end,2*n+1);
}
M[n] = M[n*2]+ M[n*2+1];
return l+r;
}
int main()
{
memset(M,0,sizeof M);
int n,m,a,b,c;
scanf("%d%d",&n,&m);
for(int i=0; i<m; i++)
{
scanf("%d%d%d",&a,&b,&c);
if(a==0)
{
update(1,n,b,c);
}
else
{
printf("%d\n",query(1,n,b,c));
}
}
return 0;
}
M[node]^=1; might be faster than M[node] = (M[node]==0)?1:0;, and (begin+end)>>1 faster than (begin/end)/2, but not very relevant
LE: Try if making the recursive functions inline will run faster. I think it unravels the recursion a couple of times and works a little bit faster. Maybe sending the parameters as references will make it run faster, try that out. If the test cases are chosen properly you still shouldn't be able to pass the tests with this trickery, but it helps sometimes.