Getting wrong answer in a DP problem although implementation looks correct - c++

I was trying to solve Reduce String on codechef which says
Give a string s of length l, and a set S of n sample string(s). We do reduce the string s using the set S by this way:
Wherever Si appears as a consecutive substring of the string s, you can delete (or not) it.
After each deletion, you will get a new string s by joining the part to the left and to the right of the deleted substring.
I wrote a recursive function as follows:-
Basically what i am doing in my code is either don't delete the character or delete it if it is part of any substring but it is giving wrong answer.
#include <bits/stdc++.h>
using namespace std;
#define mx 255
int dp[mx];
unordered_map<string,int> sol;
void init(int n)
{
for(int i=0;i<n;i++)
{
dp[i]=-1;
}
}
int solve(string str,int low,int high,vector<string> smp)
{
if(low>high)
{
return 0;
}
if(dp[low]!=-1)
{
return dp[low];
}
int ans=1+solve(str,low+1,high,smp);
for(int i=low;i<high;i++)
{
string tem=str.substr(low,i-low+1);
for(int j=0;j<smp.size();j++)
{
cout<<"low i high str"<<low<<" "<<i<<" "<<high<<" "<<smp[j]<<" "<<tem<<endl;
if(tem.compare(smp[j])==0)
{
ans=min(ans,solve(str,i+1,high,smp));
}
}
}
return dp[low]=ans;
}
signed main()
{
sol.clear();
string str;
vector<string> smp;
int n;
cin>>str;
cin>>n;
for(int i=0;i<n;i++)
{
string tem;
cin>>tem;
smp.push_back(tem);
}
int len=str.length();
init(len+1);
cout<<solve(str,0,len-1,smp)<<endl;
return 0;
}
PS:
link to the question

This question is toughest(seen so far) and most beautiful(again seen so far) question based on DP ON INTERVALS.
The initial code would definitely not work since it only considers single pass on the string and would not consider remaining string after deleting the patterns again and again.
There are 3 cases:-
Case 1 Either character is not deleted.
Case 2It is deleted as a part of contiguous substring.
Case 3It is deleted as a part of subsequence that matches any word given in the set of patterns and everything that is not part of that subsequence is deleted first as a substring(which again belongs to set of words).
The third part is the most tricky and requires enough thinking and is even tougher to implement too.
So for every substring we need to check whether this substring can be completely destroyed or not.
The function compute_full_recur() is the function that ensures that whether substring can be deleted either in Case 2 or Case 3.
The function compute_full takes care of Case 1.And finally this code will not run on codechef link since all the function are recursive with memoization but to verify the code is working i Have run it on Problem Reducto of Hackerrank which is exact similar with lower constraints.Download test cases and then run on test cases on your PC for verifying.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
#define mx 252
#define nx 40
bool full[mx][mx],vis[mx][mx],full_recur[mx][mx][nx][nx];
int ans[mx];
void init()
{
for(int i=0;i<mx;i++)
{
for(int j=0;j<mx;j++)
{
full[i][j]=false,vis[i][j]=false;
}
}
for(int i=0;i<mx;i++)
{
ans[i]=-1;
}
for(int i=0;i<mx;i++)
{
for(int j=0;j<mx;j++)
{
for(int k=0;k<nx;k++)
{
for(int l=0;l<nx;l++)
{
full_recur[i][j][k][l]=false;
}
}
}
}
}
bool compute_full_recur(string str,int low,int high,vector<string> pat,int idx,int len)
{
if(low>high&&len==pat[idx].length())
{
return true;
}
if(low>high&&len<pat[idx].length())
{
full_recur[low][high][idx][len]=false;
return false;
}
if(str[low]==pat[idx][len]&&compute_full_recur(str,low+1,high,pat,idx,len+1))
{
return full_recur[low][high][idx][len]=true;
}
for(int i=low+1;i<=high;i++)
{
if(str[low]==pat[idx][len]&&full[low+1][i]&&compute_full_recur(str,i+1,high,pat,idx,len+1))
{
return full_recur[low][high][idx][len]=true;
}
}
full_recur[low][high][idx][len]=false;
return false;
}
void compute_full(string str,int low,int high,vector<string> pats)
{
if(low>high)
{
return;
}
if(vis[low][high])
{
return;
}
vis[low][high]=true;
compute_full(str,low+1,high,pats);
compute_full(str,low,high-1,pats);
for(int i=0;i<pats.size();i++)
{
if(!full[low][high])
full[low][high]=compute_full_recur(str,low,high,pats,i,0);
}
}
int compute_ans(string str,int low,int high)
{
if(low>high)
{
return 0;
}
if(ans[low]!=-1)
{
return ans[low];
}
int sol=1+compute_ans(str,low+1,high);
for(int i=low+1;i<=high;i++)
{
if(full[low][i]==true)
{
sol=min(sol,compute_ans(str,i+1,high));
}
}
return ans[low]=sol;
}
signed main()
{
int t;
cin>>t;
while(t--)
{
string str;
int n;
vector<string> pats;
cin>>n>>str;
for(int i=0;i<n;i++)
{
string tem;
cin>>tem;
pats.push_back(tem);
}
init();
compute_full(str,0,str.length()-1,pats);
cout<<compute_ans(str,0,str.length()-1)<<endl;
}
return 0;
}

Related

SIGABRT error in cpp

I'm getting a SIGABRT error when I compile the following code(PALIN problem on SPOJ).The objective of the code is to find smallest palindromic number which should be greater than the given number, where given number can have upto 1000000 digits.
Link to the problem is: http://www.spoj.com/problems/PALIN/ It runs well on codeblocks but SPOJ returns SIGABRT error. Can someone explain the reason?
#include<iostream>
#include<string>
using namespace std;
string palinodd(string num)//to find next nearest palindrome for an odd digit number
{
string palin=num;
int flag=0;
for(int i=num.size()/2-1;i>-1;i--)
{
if(flag==0)//checks if the middle most digit should be incremented
{
if(num[i]<palin[num.size()-i-1])
flag=1;
else if(num[i]>palin[num.size()-i-1])
flag=-1;
}
palin[num.size()-1-i]=num[i];
}
if(flag!=-1)
palin[num.size()/2]++;
if(palin[num.size()/2]==':')//if the middle digit goes greater than 9
{
palin[num.size()/2]='0';
palin[num.size()/2-1]++;
palin[num.size()/2+1]++;
}
return palin;
}
string palineve(string num)//to find next nearest palindrome for an even digit number
{
string palin=num;
int flag=0;
for(int i=num.size()/2-1;i>-1;i--)
{
if(flag==0)//checks if middle digit should be incremented
{
if(num[i]<palin[num.size()-i-1])
flag=1;
else if(num[i]>palin[num.size()-i-1])
flag=-1;
}
palin[num.size()-1-i]=num[i];
}
if(flag!=-1)
palin[num.size()/2-1]++;
if(palin[num.size()/2-1]==':')//if the middle digit goes greater than 9
{
palin[num.size()/2-2]++;
palin[num.size()/2+1]++;
palin[num.size()/2-1]='0';
}
palin[num.size()/2]=palin[num.size()/2-1];//updates the middle number
return palin;
}
int main()
{
int t;
cin>>t;
while(t--)
{
string num="912496394";
string ans;
if(num.size()%2!=0)
ans=palinodd(num);
else
ans=palineve(num);
cout<<ans<<endl;
}
return 0;
}
Appreciate your effort, try to match c++ compiler, version in SPOJ and codeblocks. I tried your code with clang++-5.0 after changing num (912496394) to string but i didn't get expected results. I think you might have posted older version of your code, if possible you can post the updated code.
The process will be aborted with SIGABRT if there are any overflows in your code, as you are using more string operations you can refer below link which has some info on SIGABRT,
SIGABRT called when calling find() on a string element in an array
One suggestion on your approach to the problem, you can try to increment the input by one in a while loop until you find a palindrome or you reach largest number and print the results
The solution I found out for above problem is:
#include<iostream>
#include<string>
using namespace std;
string palinodd(string num)
{
string palin=num;
int flag=0;
for(int i=num.size()/2-1;i>-1;i--)
{
if(flag==0)
{
if(num[i]<palin[num.size()-i-1])
flag=1;
else if(num[i]>palin[num.size()-i-1])
flag=-1;
}
palin[num.size()-1-i]=num[i];
}
if(flag!=-1)
palin[num.size()/2]++;
if(palin[num.size()/2]==':')
{
palin[num.size()/2]='0';
palin[num.size()/2-1]++;
palin[num.size()/2+1]++;
}
for(int i=num.size()/2-1;i>0;i--)
{
if(palin[i]==':')
{
palin[i]='0';
palin[i-1]++;
}
}
for(int i=num.size()/2+1;i<num.size()-1;i++)
{
if(palin[i]==':')
{
palin[i]='0';
palin[i+1]++;
}
}
return palin;
}
string palineve(string num)
{
string palin=num;
int flag=0;
for(int i=num.size()/2-1;i>-1;i--)
{
if(flag==0)
{
if(num[i]<palin[num.size()-i-1])
flag=1;
else if(num[i]>palin[num.size()-i-1])
flag=-1;
}
palin[num.size()-1-i]=num[i];
}
if(flag!=-1)
palin[num.size()/2-1]++;
if(palin[num.size()/2-1]==':')
{
palin[num.size()/2-2]++;
palin[num.size()/2+1]++;
palin[num.size()/2-1]='0';
}
palin[num.size()/2]=palin[num.size()/2-1];
/*if any incremented digit becomes greater than 9,it shows a ':' so we make it 0 and increase previous(if ':' comes in the first half of the string)/next(if ':' comes in the last half of the sting) digit by 1.*/
for(int i=num.size()/2-2;i>0;i--)
{
if(palin[i]==':')
{
palin[i]='0';
palin[i-1]++;
}
}
for(int i=num.size()/2+1;i<num.size()-1;i++)
{
if(palin[i]==':')
{
palin[i]='0';
palin[i+1]++;
}
}
return palin;
}
int main()
{
int t;
cin>>t;
while(t--)
{
string num,ans;
cin>>num;
int cnt=0;
/*if all the digits in the string are 9, then the next palindromic number will have one more digit than the original number of digits. Thus, increasing the string length*/
for(int i=0;i<num.size();i++)
{
if(num[i]=='9')
cnt++;
}
if(cnt==num.size())
{
num[0]='1';
for(int i=1;i<num.size();i++)
num[i]='0';
num+='0';
}
if(num.size()%2!=0)
ans=palinodd(num);
else
ans=palineve(num);
cout<<ans<<endl;
}
return 0;
}

Prime numbers in an dynamic array

I've a program which inserts all prime numbers up to a specific number in an array.
The calculation is correct. My problems are the function parameters and the transfer of my dynamic array to the function. My function doesn't modify my array.
Please take a look at the code:
#include <iostream>
using namespace std;
int primeinlesen(int *i);
int primarrayspeicherung (int *primarray,int *bis);
int main()
{
int reload=1;
while(reload==1)
{
int bis=0,*primarray,valcounter;
primeinlesen(&bis);
valcounter=primarrayspeicherung(primarray,&bis);
for(int i=0;i<valcounter;i++)
{
cout<<i<<". Primzahl: "<<primarray[i]<<"\n";
}
delete [] primarray;
cout<<"Anzahl Primzahlen: "<<valcounter<<endl;
cout<<"Erneute Berechnung?(Ja(1) oder Nein(0))";
cin>>reload;
}
return 0;
}
int primeinlesen(int *i)
{
cout<<"Bis zu welchem Wert moechten SiePrimzahlen ausgegeben,haben(max.500)";
cin>>*i;
if(*i>500)
{
cout<<"Wert zu hoch...";
}
return 0;
}
int primarrayspeicherung (int *primarray,int *bis)
{
int x,y,counter,e,valcounter=0,xcounter=0,xvalcounter=0,xx,xy,xe;
for(x=2;x<*bis;x++)
{
counter=0;
for(y=2;y<x;y++)
{
e=x%y;
if(e==0)
{
counter++;
}
}
if(counter==0)
{
valcounter++;
}
}
//ZWEITER DURCHGANG
primarray=new int[valcounter];
for(xx=2;xx<*bis;xx++)
{
xcounter=0;
for(xy=2;xy<xx;xy++)
{
xe=xx%xy;
if(xe==0)
{
xcounter++;
}
}
if(xcounter==0)
{
primarray[xvalcounter]=xx;
xvalcounter++;
}
}
return valcounter;
}
Best regards
In this function:
int primarrayspeicherung (int *primarray,int *bis)
primarray is a local variable. Everything you're doing to it (e.g. allocating, assigning) only affects the local primarray, not the one you pass in. If you want to modify both, you need to pass in a reference:
int primarrayspeicherung (int*& primarray,int *bis)

NFA simulator error C++

I have one big problem with my NFA simulator.
When I run the code sometimes everything goes nice, but sometimes I get this
Process terminated with status -1073741819(0xC0000005)
What do I miss out and what to do to get this work fine?
This is the code:
#include <iostream>
#include<fstream>
#include<map>
using namespace std;
ifstream fin("fisier.txt");
class NFA {
int initiala,finale,stari,tran,cuvinte;
int *f;
multimap <pair <int,int>,char>t;
public:
void stari_finale();
void tranzitii();
void rezolvare();
};
void NFA::stari_finale()
{
fin>>finale;
f=new int[finale];
for(int i=1;i<=finale;i++)
fin>>f[i];
}
void NFA::tranzitii()
{
fin>>tran;
for(int i=1;i<=tran;i++)
{
int x,y;
char c2;
fin>>x>>y>>c2;
t.insert(make_pair(make_pair(x,y),c2));
}
}
void NFA::rezolvare()
{
fin>>stari>>initiala;
fin>>cuvinte;
for(int i=1;i<=cuvinte;i++)
{
int l;
fin>>l;
char *cuv=new char[l+1];
fin.get();
fin.getline(cuv,l+1);
int *c=new int[stari],nr=1;
c[1]=initiala;
for(int j=0;j<l;j++)
{
int *c1=new int[stari];
int n=0;
for(int k=1;k<=nr;k++)
for(int z=0;z<=stari;z++)
if(t.find(make_pair(c[k],z))!=t.end())
if(t.find(make_pair(c[k],z))->second==cuv[j])
n++,c1[n]=z;
for(int k=1;k<=n;k++)
c[k]=c1[k];
nr=n;
delete c1;
}
for(int j=1;j<=nr;j++)
{for(int k=1;k<=finale;k++)
if(c[j]==f[k])
{
cout<<"Word "<<cuv<<" is accepted!\n";
nr=-1;
break;
}
if(nr==-1)
break;
}
if(nr!=-1)
cout<<"Word "<<cuv<<" isn't accepted!\n";
delete c;
delete cuv;
}
}
int main()
{
NFA test;
test.stari_finale();
test.tranzitii();
test.rezolvare();
return 0;
}
One major problem is you are not calling the right delete on your variables. If you call new you need to call delete. If you call new[] you need to use delete[]. Mixing new[] and delete calls will cause undefined behavior which is a symptom of what is happening.
Your calls to delete for c, c1 and cuv should all be delete [] variable_name
You are writing outside the array here:
void NFA::stari_finale()
{
fin>>finale;
f=new int[finale];
for(int i=1;i<=finale;i++)
fin>>f[i];
}
f has the size finale, but i will be equal to finale in the last iteration.
Use this instead:
void NFA::stari_finale()
{
fin>>finale;
f=new int[finale];
for(int i=0;i<finale;i++)
fin>>f[i];
}
or, if you really need to use the 1-based indexing:
void NFA::stari_finale()
{
fin>>finale;
f=new int[finale + 1];
for(int i=1;i<=finale;i++)
fin>>f[i];
}

Palindrome Partitioning (how to figure out how to use DFS)

My general question is how to figure out how to use DFS. It seems to be a weak part of my knowledge. I have vague idea but often get stuck when the problem changes. It caused a lot of confusion for me.
For this question, I got stuck with how to write DFS with recursion.
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab",
Return
[
["aa","b"],
["a","a","b"]
]
My first attempt was stuck in the loop of the helper function. Then from searching on internet, I found that bool palindrome(string s) can be written as a different signature.
bool palindrome(string &s, int start, int end)
This leads to the correct solution.
Here's the code of my initial attempt:
class Solution {
public:
bool palindrome(string s)
{
int len = s.size();
for (int i=0;i<len/2; i++)
{
if (s[i]!=s[len-i])
return false;
}
return true;
}
void helper( int i, string s, vector<string> &p, vector<vector<string>> &ret)
{
int slen = s.size();
if (i==slen-1&&flag)
{
ret.push_back(p);
}
for (int k=i; k<slen; k++)
{
if (palindrome(s.substr(0,k)))
{
p.push_back(s.substr(0,k)); //Got stuck
}
}
i++;
}
vector<vector<string>> partition(string s) {
vector<vector<string>> ret;
int len=s.size();
if (len==0) return ret;
vector<string> p;
helper(0,s,p,ret);
return ret;
}
};
Correct one:
class Solution {
public:
bool palindrome(string &s, int start, int end)
{
while(start<end)
{
if (s[start]!=s[end])
return false;
start++;
end--;
}
return true;
}
void helper( int start, string &s, vector<string> &p, vector<vector<string>> &ret)
{
int slen = s.size();
if (start==slen)
{
ret.push_back(p);
return;
}
for (int i=start; i<s.size(); i++)
{
if (palindrome(s, start, i))
{
p.push_back(s.substr(start,i-start+1));
helper(i+1,s,p,ret);
p.pop_back();
}
}
}
vector<vector<string>> partition(string s) {
vector<vector<string>> ret;
int len=s.size();
if (len==0) return ret;
vector<string> p;
helper(0,s,p,ret);
return ret;
}
};
Edit Dec. 4, 2014: I saw some approach using dynamical programming but can't understand the code completely.
esp. isPalin[i][j] = (s[i] == s[j]) && ((j - i < 2) || isPalin[i+1][j-1]);
Why j-I<2 instead of j-I<1?
class Solution {
public:
vector<vector<string>> partition(string s) {
int len = s.size();
vector<vector<string>> subPalins[len+1];
subPalins[0] = vector<vector<string>>();
subPalins[0].push_back(vector<string>());
bool isPalin[len][len];
for (int i=len-1; i>=0; i--)
{
for (int j=i; j<len; j++)
{
isPalin[i][j] = (s[i]==s[j])&&((j-i<2)||isPalin[i+1][j-1]);
}
}
for (int i=1; i<=len;i++)
{
subPalins[i]=vector<vector<string>>();
for (int j=0; j<i; j++)
{
string rightStr=s.substr(j,i-j);
if (isPalin[j][i-1])
{
vector<vector<string>> prepar=subPalins[j];
for (int t=0; t<prepar.size(); t++)
{
prepar[t].push_back(rightStr);
subPalins[i].push_back(prepar[t]);
}
}
}
}
return subPalins[len];
}
};
What exactly are you asking? You have correct working code and your non-working code which is not that different.
I guess I can point out several issues with your code - may be it will be helpful to you:
in the palindrome() function you should compare s[i] to s[len-1-i] rather than to just s[len-i] in the if, since in former case you will compare 1st element (having index 0) to the non-existent element (index len). That might be the reason helper() got stuck.
in the helper() function flag is not initialized. In the for cycle, the end condition should be k<slen-1 instead of k<slen, since in latter case you will omit checking the substring that includes the terminal symbol of the string. Also, incrementing i in the end of helper() is pointless. Finally, indentations are messy in the helper() function.
Not sure why you use DFS - what is the meaning of your graph, what are the vertices and edges here? As to how the recursion works here: in the helper() function you start checking substrings of increased length for being palindrome. If the palindrome is found, you place it into p vector (which represent your current partitioning) and try to break the remainder of the string into palindromes by calling helper() recursively. If you succeed in that (i.e. if the whole string is completely partitioned into palindromes) you place the contents of p vector (current partitioning) into ret (set of all found partitionings), and then clear p to prepare it for the analysis of the next partition (purge of p is achieved by pop_back() call that follows recursive call of helper()). If, on the other hand, you fail to completely break string into palindromes, the p is purged as well, but without transferring its content into ret (this is due to the fact that recursive call for the last piece of string - which is not a palindrome - returns without calling helper() for the final symbol and thus pushing p into ret does not occur). Therefore you end up having all possible palindrome partitionings in the ret.
Hi~ this is my code using DFS + backtracking.
class Solution
{
public:
bool isPalindrome (string s) {
int i = 0, j = s.length() - 1;
while(i <= j && s[i] == s[j]) {
i++;
j--;
}
return (j < i);
}
void my_partition(string s, vector<vector<string> > &final_result, vector<string> &every_result ) {
if (s.length() ==0)
final_result.push_back(every_result);
for (int i =1; i <= s.length();++i) {
string left = s.substr(0,i);
string right = s.substr(i);
if (isPalindrome(left)) {
every_result.push_back(left);
my_partition(right, final_result, every_result);
every_result.pop_back();
}
}
}
vector<vector<string>> partition(string s) {
vector<vector<string> > final_result;
vector<string> every_result;
my_partition(s, final_result, every_result);
return final_result;
}
};
I have done Palindrome Partitioning using backtracking. Depth-first search was used here, idea is to split the given string so that the prefix is a palindrome. push prefix in a vector now explore the string leaving that prefix and then finally pop the last inserted element,
Well on spending time on backtracking is of the form, choose the element, explore without it and unchoose it.
enter code here
#include<iostream>
#include<vector>
#include<string>
using namespace std;
bool ispalidrome(string x ,int start ,int end){
while(end>=start){
if(x[end]!=x[start]){
return false;
}
start++;
end--;
}
return true;
}
void sub_palidrome(string A,int size,int start,vector<string>&small, vector < vector < string > >&big ){
if(start==size){
big.push_back(small);
return;
}
for(int i=start;i<size;i++){
if( ispalidrome(A,start,i) ){
small.push_back(A.substr(start,i-start+1));
sub_palidrome(A,size,i+1,small,big);
small.pop_back();
}
}
}
vector<vector<string> > partition(string A) {
int size=A.length();
int start=0;
vector <string>small;
vector < vector < string > >big;
sub_palidrome(A,size,start,small,big);
return big;
}
int main(){
vector<vector<string> > sol= partition("aab");
for(int i=0;i<sol.size();i++){
for(int j=0;j<sol[i].size();j++){
cout<<sol[i][j]<<" ";
}
cout<<endl;
}
}

Generating permutation of string without duplicates [duplicate]

This question already has answers here:
Finding all the unique permutations of a string without generating duplicates
(5 answers)
Closed 9 years ago.
I have writing a general program to generate permutation of string but removing the duplicate cases . For this I am using memorization by using .
void permute(char *a,int i, int n,set<char*> s)
{
if(i==n)
{
if(s.find(a)==s.end()){
cout<<"no dublicate"<<endl;
cout<<a<<endl;
s.insert(a)
}
}
else{
for(int j=i;j<n;j++)
{
swap(a[i],a[j]);
permute(a,i+1,n,s);
swap(a[i],a[j]);
}
}
}
int main()
{
char a[]="aba";
set <char*> s;
permute(a,0,3,s);
return 0;
}
But the result is not as desired. It prints all the permutation. Can anyone help me in figuring out the problem.
First, you pass set<> s parameter by value, which discards your each insert, because it's done in the local copy of s only. However even if you change it to pass by reference, it won't work, because every time you insert the same char* value, so only one insert will be done. To make your code work correctly I suggest to change the prototype of your function to
void permute(string a,int i, int n,set<string>& s)
and this works all right.
update: source code with described minor changes
void permute(string a,int i, int n,set<string>& s)
{
if(i==n)
{
if(s.find(a)==s.end()){
cout<<"no dublicate"<<endl;
cout<<a<<endl;
s.insert(a);
}
}
else{
for(int j=i;j<n;j++)
{
swap(a[i],a[j]);
permute(a,i+1,n,s);
swap(a[i],a[j]);
}
}
}
int main()
{
string a ="aba";
set <string> s;
permute(a,0,3,s);
return 0;
}