SWPDGT - Editorial

PROBLEM LINK:

Practice
Contest: Division 1
Contest: Division 2

Setter: Farhan Hasin
Tester: Teja Vardhan Reddy
Editorialist: Taranpreet Singh

DIFFICULTY:

Cakewalk

PREREQUISITES:

None

PROBLEM:

Given two integers A and B where 1 \leq A, B \leq 99, you are allowed to swap at most one pair of digit among A and B. What is the maximum value of A+B you can get?

QUICK EXPLANATION

  • Since each number can consist of at most 2 digits, we can manually check all four possible swaps and print the maximum value.

EXPLANATION

Let’s assume A \geq B. We can consider four cases.

  • When A, B < 10
    In this case, swapping doesn’t change the answer at all.
  • When A < 10 \leq B
    In this case, we can try swapping A with both digits of B and calculate A+B in each case and take maximum.
  • When A, B \geq 10
    We can consider all four swaps (first digit of A with first digit of B, first digit of A with the second digit of B and so on) and take maximum.

Bonus: Can you solve it without explicitly doing swaps and then comparing?

Solution

Assume A1 be first digit of A, A2 be second digit of A. Similarly, B1 is first digit of B and B2 is second digit of B.

So A+B = (A1+B1)*10+(A2+B2). We try to swap larger one of A2 and B2 with smaller one of A1 and B1 if it increases A+B.

TIME COMPLEXITY

The time complexity is O(1) per test case.

SOLUTIONS:

Setter's Solution
#include <bits/stdc++.h>

using namespace std;
typedef long long ll;

int main() {

	//freopen("testcases.txt","r",stdin);

	int t;
	cin>>t;

	while(t--) {
	    int a,b;
	    cin>>a>>b;


	    int mx=a+b;

	    int a1=a%10;
	    int a2=a/10;

	    int b1=b%10;
	    int b2=b/10;

	    
	    mx=max(mx,a2*10+b1+b2*10+a1);
	    if(b2) mx=max(mx,a2*10+b2+a1*10+b1);
	    if(a2) mx=max(mx,b1*10+a1+b2*10+a2);
	    if(a2 && b2) mx=max(mx,b2*10+a1+a2*10+b1);

	    cout<<mx<<endl;

	}

	return 0;
}
Tester's Solution
//teja349
#include <bits/stdc++.h>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <climits>
#include <utility>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <iomanip>
//setbase - cout << setbase (16); cout << 100 << endl; Prints 64
//setfill -   cout << setfill ('x') << setw (5); cout << 77 << endl; prints xxx77
//setprecision - cout << setprecision (14) << f << endl; Prints x.xxxx
//cout.precision(x)  cout<<fixed<<val;  // prints x digits after decimal in val
 
using namespace std;
 
#define f(i,a,b) for(i=a;i<b;i++)
#define rep(i,n) f(i,0,n)
#define fd(i,a,b) for(i=a;i>=b;i--)
#define pb push_back
#define mp make_pair
#define vi vector< int >
#define vl vector< ll >
#define ss second
#define ff first
#define ll long long
#define pii pair< int,int >
#define pll pair< ll,ll >
#define inf (1000*1000*1000+5)
#define all(a) a.begin(),a.end()
#define tri pair<int,pii>
#define vii vector<pii>
#define vll vector<pll>
#define viii vector<tri>
#define mod (1000*1000*1000+7)
#define pqueue priority_queue< int >
#define pdqueue priority_queue< int,vi ,greater< int > >
#define flush fflush(stdout) 
#define primeDEN 727999983
 

int main(){
	std::ios::sync_with_stdio(false); cin.tie(NULL);
	int t;
	cin>>t;
	while(t--){
		int a,b;
		cin>>a>>b;
		int sumi=a+b;
		int ans=0;
		if(a>=10){
			ans=a/10+a%10+(b%10+b/10)*10;
			sumi=max(sumi,ans);
		}
		swap(a,b);
		if(a>=10){
			ans=a/10+a%10+(b%10+b/10)*10;
			sumi=max(sumi,ans);
		}
		cout<<sumi<<endl;
	}

}
Editorialist's Solution
import java.util.*;
import java.io.*;
import java.text.*;
class SWPDGT{
	//SOLUTION BEGIN
	void pre() throws Exception{}
	void solve(int TC) throws Exception{
	    int a = ni(), b = ni();
	    int ans = a+b;
	    if(a< 10){
	        if(b< 10)ans = Math.max(ans, a+b);
	        else{
	            int b1 = b/10, b2 = b%10;
	            ans = Math.max(ans, b1+a*10+b2);
	            ans = Math.max(ans, b2+b1*10+a);//Prove this is useless
	        }
	    }else{
	        if(b < 10){
	            int a1 = a/10, a2 = a%10;
	            ans = Math.max(ans, a1+b*10+a2);
	            ans = Math.max(ans, a2+a1*10+b);//Prove this is useless
	        }else{
	            int a1 = a/10, a2 = a%10;
	            int b1 = b/10, b2 = b%10;
	            
	            ans = Math.max(ans, a1*10+b2+ b1*10+a2);//Prove this is useless
	            ans = Math.max(ans, b1*10+a2+ a1*10+b2);//Prove this is useless
	            ans = Math.max(ans, a1*10+b1 + a2*10+b2);
	            ans = Math.max(ans, b2*10+a2+ b1*10+a1);
	        }
	    }
	    pn(ans);
	}
	//SOLUTION END
	void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
	DecimalFormat df = new DecimalFormat("0.00000000000");
	static boolean multipleTC = true;
	FastReader in;PrintWriter out;
	void run() throws Exception{
	    in = new FastReader();
	    out = new PrintWriter(System.out);
	    //Solution Credits: Taranpreet Singh
	    int T = (multipleTC)?ni():1;
	    pre();for(int t = 1; t<= T; t++)solve(t);
	    out.flush();
	    out.close();
	}
	public static void main(String[] args) throws Exception{
	    new SWPDGT().run();
	}
	int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
	void p(Object o){out.print(o);}
	void pn(Object o){out.println(o);}
	void pni(Object o){out.println(o);out.flush();}
	String n()throws Exception{return in.next();}
	String nln()throws Exception{return in.nextLine();}
	int ni()throws Exception{return Integer.parseInt(in.next());}
	long nl()throws Exception{return Long.parseLong(in.next());}
	double nd()throws Exception{return Double.parseDouble(in.next());}

	class FastReader{
	    BufferedReader br;
	    StringTokenizer st;
	    public FastReader(){
	        br = new BufferedReader(new InputStreamReader(System.in));
	    }

	    public FastReader(String s) throws Exception{
	        br = new BufferedReader(new FileReader(s));
	    }

	    String next() throws Exception{
	        while (st == null || !st.hasMoreElements()){
	            try{
	                st = new StringTokenizer(br.readLine());
	            }catch (IOException  e){
	                throw new Exception(e.toString());
	            }
	        }
	        return st.nextToken();
	    }

	    String nextLine() throws Exception{
	        String str = "";
	        try{   
	            str = br.readLine();
	        }catch (IOException e){
	            throw new Exception(e.toString());
	        }  
	        return str;
	    }
	}
}

Feel free to share your approach. Suggestions are welcomed as always. :slight_smile:

3 Likes

there are two numbers like a and b , first divide a by 10 and save in one variable whose data type is integer and and substract this variable in a like this ;
int temporary1=a/10;
int temporary2=a%10;
int add1=temporary1+temporary2;
you want to do this process for also number b and find new variable add2(like add1) and you want to convert add1 and add2 in string with help of .ToString() function and combine two string (String add=add2 +add1;)
and print this string as answer and also you can convert string to integer .so that is my view and thank you for read this reply.

What if we make all the possible combinations by swapping digits, append all in a list and print maximum of all ? The method don’t give correct answer. please explain the mistake.
Here is my code in python:

num = int(input())
for i in range(0,num):
add = []
li = input().split()
for m in li[0]:
for k in li[1]:
s = li[1].replace(k,m)
s1 = li[0].replace(m,k)
add.append(int(s)+int(s1))
add.append(int(li[0])+int(li[1]))
print(max(add))

@sam_p30 I had the same logic. I made all possible combinations from the numbers, and then printed maximum, but I got WA.

Here is my code in c++: https://www.codechef.com/viewsolution/30848565

1 Like

You are adding all digits like unit digits

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;

int main() {

int t;
cin>>t;

while(t--) {
    int a,b;
    cin>>a>>b;


    int mx=a+b;

    int a1=a%10;
    int a2=a/10;

    int b1=b%10;
    int b2=b/10;

    
    if(b2) mx=max(mx,a2*10+b2+a1*10+b1);
    if(a2) mx=max(mx,b1*10+a1+b2*10+a2);

    cout<<mx<<endl;

}

return 0;

}
//1-mx=max(mx,a210+b1+b210+a1);
//2-if(a2 && b2) mx=max(mx,b210+a1+a210+b1);
you can also remove these conditions from your code
becoz-
1- statement is swapping only ones’s digit of both the numbers,which would not affect the sum
eg - 45+76=121 and 75+46=121
2-statement is swapping only ten’s digit of both numbers ,if they both are double digit numbers,which would again wont affect the sum as even if both are single digit or one of them is single and other is double digit it WONT AFFECT the sum
eg-34+52=86 and 32+54=86 both are equal

3 Likes

please can anyone point me out why it gives WA @taran_1407

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int tc,x;
    cin>>tc;
    for(x=0;x<tc;x++){
        int a,b,i,max1=0;
        int sum[5],dig[4];
        cin>>a>>b;
        dig[0]=a/10;
        dig[1]=a%10;
        dig[2]=b/10;
        dig[3]=b%10;
        sum[0]=a+b;
        max1=sum[0];
        sum[1]=(((dig[0]*10)+dig[3])+((dig[2]*10)+dig[1]));
        sum[2]=(((dig[0]*10)+dig[2])+((dig[1]*10)+dig[3]));
        sum[3]=(((dig[2]*10)+dig[1])+((dig[0]*10)+dig[3]));
        sum[4]=(((dig[3]*10)+dig[1])+((dig[2]*10)+dig[0]));
        for(i=1;i<5;i++){
            if(max1<sum[i]){
                max1=sum[i];
            }
        }
        cout<<max1<<"\n";
    }
    return 0;
}

1
99 9
Actual output :- 189
Expected Output :- 108
You are not supposed to find sum[4] for (9,99) and sum[2] for reverse of this test case(99,9) for this kind of test cases. Because test case can be interpreted like(99,09) and if you swap dig[3] with dig[2] i.e (90,99). since zero does not hold any value before a number(for 2 digit number) and add them surely it is going to give wa.
For single digit test cases like (1,3) and (3,1) you should not calculate sum[4] and sum[2].

3 Likes

can you please tell me what is wrong with my solution

This is all what i have done by the edtorial.
Anyone please help.

Hi everyone . I want help from the pro coders here, can you check whats wrong with my python code for this question, it will be a big help .

https://www.codechef.com/viewsolution/30923586

please check why my code is giving WA …
#include<iostream.h>
#include<bits/stdc++.h>
using namespace std;

int main() {
// your code goes here
int t;
cin>>t;
while(t–>0)
{
int a,b;
cin>>a>>b;
int sum=0;
sum=a+b;
int a1=0,b1=0,b2=0,a2=0;
a1=a/10;
a2=a%10;
b1=b/10;
b2=b%10;
if(a1==0 && b1==0);
if(a1==0 && b1!=0)
{
if((a2 * 10 + b1+ b2 )>sum)
sum=a2* 10 + b1+ b2 ;
}
else if(b1==0 && a1!=0)
{
if(( b2 * 10 + a1 + a2 )>sum)
{
sum=b2*10 + a1 + a2;

        }
    }
    else 
    {
        if((a1*10+ a2*10 + b1 +b2)>sum)
        {
            sum=(a1+a2)*10 + b1 +b2;
        }
       else if((b1*10+b2*10 + a1+ a2)>sum)
        {
            sum=(b1+b2)*10 + a1+ a2;
        }
    }
    cout<< sum <<endl;
    
        
}
return 0;

}

can someone help me ? why it doesnt accept my solution?
#include<stdio.h>

int main(){
int A,B,i=2,j=2,array[3]={},array2[3]={},a,T,T2,T3,k;
printf(“How many test do you want?\n”);
scanf("%d",&T2);

if(T2>=1 && T2<=1000){

do{
	for(i=0;i<3;i++){
		array[i]=0;
		array2[i]=0;
	}
printf("enter 2 number.\n");
scanf("%d %d",&A,&B);
if(A<100&& A>0 && B>0 && B<100){
T=A;i=2;j=2;
while(T!=0){
	a=T%10;
	array[i]=a;         
	i--;
	T=T/10;
}
T=B;
while(T!=0){
	a=T%10;
	array2[j]=a;
	j--;
	T=T/10;
}

if(array[2]>array2[1] && array[2]>array2[2] && array2[1]!=0 ){
	T3=array[2];
	array[2]=array2[1];
	array2[1]=T3;
}
else if(array[1]<array2[2] && array2[2]>array[2] && array[1]!=0){
	T3=array[1];
	array[1]=array2[2];
	array2[2]=T3;
}
else if(array[1]<array2[2] && array[1]!=0){
	T3=array[1];
	array[1]=array2[2];
	array2[2]=T3;
}
else if(array[2]>array2[1] && array2[1]!=0){
	T3=array[2];
	array[2]=array2[1];
	array2[1]=T3;
}
array[0]=array[1]*10+array[2];
array2[0]=array2[1]*10+array2[2];
printf("%d\n",array[0]+array2[0]);
k++;

}
}while(k!=T2);
}
return 0;
}

Can someone please tell in which test cases my code fails? It is showing WA

cook your dish here

for _ in range(int(input())):
    a,b=input().split()
    unit1=int(a[-1])
    unit2=int(b[-1])
    tens1=(int(a[0]) if len(a)==2 else 0)
    tens2=(int(b[0]) if len(b)==2 else 0)
    if (unit1>tens2 and tens2!=0):
        unit1,tens2=tens2,unit1
    elif (unit2>tens1 and tens1!=0):
        unit2,tens1=tens1,unit2
    print(((tens1+tens2)*10)+(unit2+unit1))

why my solution is not accepted?
i am checking manual test cases and getting correct answers but judge is not accepting the solution.please check my approach …

#include
using namespace std;

int main() {
// your code goes here
int t;
cin>>t;
for(int i=0;i<t;i++)
{
int a,b;
cin>>a>>b;
if(a<10&&b<10)
{
cout<<a+b<<endl;
}
else if(a<10&&b>=10)
{
int c=(b/10);
int d=(a*10)+(b%10);

       int e=b%10;
       int f=b-(b%10)+a;
       
       if(a+b>c+d && a+b>e+f)
       cout<<a+b<<endl;
       else if(c+d>a+b && c+d>e+f)
       cout<<c+d<<endl;
       else
       cout<<e+f<<endl;
    }
    
     else if(b<10&&a>=10)
    {
       int c=(a/10);
       int d=(b*10)+(a%10);
       
       int e=a%10;
       int f=a-(a%10)+b;
       
       if(b+a>c+d && b+a>e+f)
       cout<<b+a<<endl;
       else if(c+d>b+a && c+d>e+f)
       cout<<c+d<<endl;
       else
       cout<<e+f<<endl;
    }
    
    else
    {
        int c=(a%10)+(b-b%10);
        int d=(b%10)+(a-a%10);
        
        int e=(a%10)+(b%10)*10;
        int f=(b-b%10)+a/10;
        
        int g=(a-a%10)+b/10;
        int h=(b%10)+(a%10)*10;
        
        int i=(a-a%10)+b%10;
        int j=(b-b%10)+a%10;
        
        if(a+b>c+d&&a+b>e+f&&a+b>g+h&&a+b>i+j)
        cout<<a+b<<endl;
        else if(c+d>a+b&&c+d>e+f&&c+d>g+h&&c+d>i+j)
        cout<<c+d<<endl;
        else if(e+f>c+d&&e+f>a+b&&e+f>g+h&&e+f>i+j)
        cout<<e+f<<endl;
        else if(g+h>c+d&&g+h>a+b&&g+h>e+f&&g+h>i+j)
        cout<<g+h<<endl;
        else
        cout<<i+j<<endl;
    }
}
return 0;

}

Can anyone explain what is wrong in my approach?

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

typedef long long int ll;
typedef unsigned long long int llu;

#define gcd(a,b)    __gcd(a,b)

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int t;
    cin>>t;
    while(t--){
        string a,b;
        cin>>a>>b;
        int mina,minb;
        int indexa,indexb;
        if(a.size()==1){
            mina=a[0];
            indexa=0;
        }
        else{
            if(a[0]<=a[1]){
                mina=a[0];
                indexa=0;
            }
            else{
                mina=a[1];
                indexa=1;
            }
        }
        if(b.size()==1){
            minb=b[0];
            indexb=0;
        }
        else{
            if(b[0]<=b[1]){
                minb=b[0];
                indexb=0;
            }
            else{
                minb=b[1];
                indexb=1;
            }
        }
        //cout<<mina-48<<" "<<minb-48<<" "<<indexa<<" "<<indexb<<endl;
        a[indexa]=minb;
        b[indexb]=mina;
        int x,y;
        if(a.size()==1){
            x=a[0]-48;
        }
        else{
            x=(a[0]-48)*10+(a[1]-48);
        }
        if(b.size()==1){
            y=b[0]-48;
        }
        else{
            y=(b[0]-48)*10+(b[1]-48);
        }
        cout<<x+y<<endl;
    }
    return 0;
}

Can somebody help, why is my code giving wrong answer.
https://www.codechef.com/viewsolution/32158818

Really, it’s good to know.

why do we have to put the if(b2) and if(a2) condition without that also well get the same answer na?

You have to consider all the four cases. That are:
if a and b are numbers:
1st case : a>=10 and b>=10
2nd case : a>=10 and b<10
3rd case : a<10 and b>=10
4th case : a<10 and b<10

Here is the link to my code : https://www.codechef.com/viewsolution/34517742

Hope it helps…