0

This is my first attempt at LCS. The problem I have is with the last portion. When the two input strings are 'mango' and 'man', it seems that cout keeps messing up the 'maxseq-x.length()' part. But it seems fine when storing the result in a variable beforehand or just using printf(). Am I missing something?

#include<bits/stdc++.h>
using namespace std;

int main(){

    string x, y;
    cin >> x >> y;
    int lcs[100][100] = {{0}};
    for(int i = 0; i<y.length(); i++){
        for(int j = 0; j<x.length(); j++){
            if(y[i] == x[j]){
                int ans = 0;
            
                if(i && j){
                    ans = max(1+lcs[i-1][j-1], ans);
                }
                else{
                    ans = max(1, ans);
                }
                lcs[i][j] = ans;
            }
            else{
                int ans = 0;
                if(i){
                    ans = max(lcs[i-1][j], ans);
                }
                if(j){
                    ans = max(lcs[i][j-1], ans);
                }
                lcs[i][j] = ans;
            }   
        }
    }
    int maxseq = lcs[y.length()-1][x.length()-1];

    int z = maxseq-x.length();
    cout << maxseq-x.length() << endl;
    printf("%d\n", maxseq-x.length());
    cout << z << endl; 
    return 0;
}
A.H.M. Annur
  • 110
  • 1
  • 8
  • How exactly does ist "mess up"? – Jerome Reinländer Feb 07 '18 at 14:14
  • The printf() and z both give -2 on 'mango' & 'man' but direct cout is printing 4294967294 – A.H.M. Annur Feb 07 '18 at 14:17
  • There's probably an answer on here referencing C++ rather than C, but https://stackoverflow.com/questions/7221409/is-unsigned-integer-subtraction-defined-behavior has it. As you're not assigning to an int, the result of your operation involving an unsigned is itself unsigned. – Pete Kirkham Feb 07 '18 at 14:32

1 Answers1

0

cout handles maxseq-x.length() as unsigned value. (This expression contains both signed and unsigned values, so result is unsigned)

%d in printf handles maxseq-x.length() as signed integer

cout << z handles z as signed integer.

  • Ah! Thank You. I think I understand now. Another follow up question. Is there any way to make cout handle that part as a signed value(Without assigning to a variable)? – A.H.M. Annur Feb 07 '18 at 15:09
  • You can cast it to signed type. For example `reiterpret_cast(maxseq-x.length())` – WalterWhile Feb 07 '18 at 18:51