Hello coders, I am new to SPOJ. The problem JULKA is giving me a wrong answer (WA). I have tried with as many test cases as possible and was not able to find what is going wrong.
Kindly give me a hint on what is happening wrong in my code. I am posting it below.
include
include
include
using namespace std;
define LL long long int
define FOR(a,b,c) for (int (a)=(b); (a)<(c); (a)++)
define FORN(a,b,c) for (int (a)=(b); (a)<=(c); (a)++)
define FORD(a,b,c) for (int (a)=(b); (a)>=(c); (a)--)
void print(int *a,int size)
{
FOR(i,0,size) cout<<a[i]<< " ";cout<<endl;
}
void printR(int *a,int size)
{
FORD(i,size-1,0) cout<<a[i]; cout<<endl;
}
int dosum(int *a,int akasize,int *b,int bkasize,int *sum)
{
int n=akasize; int m=bkasize;
int carry=0,i=0,j=0,x,k=0;
while(i<n&&j<m)
{
x=a[i]+b[j]+carry;
sum[k]=x%10;
carry=x/10;
k++;i++;j++;
}
while(i<n)
{
x=a[i]+carry;
sum[k]=x%10;
carry=x/10;
k++;i++;
}
while(j<m){
x=b[j]+carry;
sum[k]=x%10;
carry=x/10;
k++;j++;
}
if(carry!=0) sum[k++]=carry;
return k;
}
int dodiff(int *a,int akasize,int *b,int bkasize,int *diff)
{
int n=akasize; int m=bkasize;
int carry=0,i=0,j=0,x,k=0;
while(i<n&&j<m){
if(a[i]-b[j]-carry<0){
diff[k]=a[i]-b[j]-carry+10;
carry=1;
}
else{
diff[k]=a[i]-b[j]-carry;
carry=0;
}
i++;j++;k++;
}
while(i<n){
diff[k]=a[i]-carry;
carry=0;k++;i++;
}
while(diff[k]==0) k--;
return k+1;/// why do we return k and not k+1
}
int divideby2(int *a,int size)
{
int n=size;int x=0;int l=0;
FORD(i,n-1,0){
l=(a[i]+x);
a[i]=l/2;
if(l%2==1){
x=10;
}
else{
x=0;
}
}
if(a[n-1]==0){
return n-1;
}
else return n;
}
int main() {
int tc;cin>>tc;
FOR(t_c,0,tc){
int *a=new int[1000];
int *b=new int[1000];
int i=0,size_a=0,size_b=0;
string s;
cin>>s;
size_a=s.length();reverse(s.begin(),s.end());
FOR(i,0,size_a){
a[i]=s[i]-'0';
}
cin>>s;
size_b=s.length();reverse(s.begin(),s.end());
FOR(i,0,size_b){
b[i]=s[i]-'0';
}
int *sum=new int [1000];int sizeofsum=0;
int *diff=new int [1000];int sizeofdiff=0;
if(size_a>=size_b){
sizeofsum= dosum(a,size_a,b,size_b,sum);
sizeofdiff=dodiff(a,size_a,b,size_b,diff);
}
else{
sizeofsum= dosum(b,size_b,a,size_a,sum);
sizeofdiff=dodiff(b,size_b,a,size_a,diff);
}
/* */
sizeofsum=divideby2(sum,sizeofsum);
sizeofdiff=divideby2(diff,sizeofdiff);
printR(sum,sizeofsum);
printR(diff,sizeofdiff);
}
return 0;
}