10055 - Hashmat the Brave Warrior

12:13 AM | , , , , , , ,



Hashmat is a brave warrior who with his group of young soldiers moves from one place to another to fight against his opponents. Before fighting he just calculates one thing, the difference between his soldier number and the opponent's soldier number. From this difference he decides whether to fight or not. Hashmat's soldier number is never greater than his opponent. The problem is make a program which finding difference of his soldier and his opponent's soldier. For the complete information read from http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=94&page=show_problem&problem=996.

Here is solution with java code

import java.util.Scanner;
class Hasmit {
    public static void main(String[] args) {
        Scanner inp=new Scanner(System.in);
        while(inp.hasNextLong()){
            long hasmit=inp.nextLong();
            long opp=inp.nextLong();
            long diff=Math.abs(opp-hasmit);
            System.out.println(diff);
        }
    }
}


 Here is solution with C++code
#include <iostream>
using namespace std;
int main() {
   long hasmit,opp;
   while(cin>>hasmit>>opp){
      long diff=opp-hasmit;
      if(diff<0) diff*=-1;
      cout<<diff<<endl;
   }
  return 0;
}

Here is solution with C code

#include <stdio.h>
main() {
   int hasmit,opp,diff;
   while(scanf("%d%d",&hasmit,&opp)!=EOF){
      diff=abs(opp-hasmit);
      printf("%d \n",diff);
   }
}

I used redirection standard input of  gcc , g++ and java compiler to execute codes on linux. You can use this code to build and test program but before it you must install gcc , g++  or jdk fisrt on your machine.
Here is the code:

alircute@alircute-Laptop:~$ g++ Hasmit.cpp -o Hasmit++
alircute@alircute-Laptop:~$ gcc Hasmit.c -o Hasmit
alircute@alircute-Laptop:~$ javac Hasmit.java
alircute@alircute-Laptop:~$ ./Hasmit++ < Hasmit.txt
420
3
11
2
alircute@alircute-Laptop:~$ ./Hasmit < Hasmit.txt
420
3
11
2
alircute@alircute-Laptop:~$ java Hasmit < Hasmit.txt
420
3
11
2
alircute@alircute-Laptop:~$

 The blue lines are source code that you execute and the red one is output program.


I just a newbie programmer , so if you have better algorithm than I. I would  so happy  if you share it  to me on my email address : etnoarelz@gmail.com  or  my Yahoo Messanger : alir.etno@yahoo.com


2 comments:

Anonymous said...

how can you handle large inputs in c..?
as the problem says input is not greater than 2^32.

Alir Retno said...

As long as we know the maximum integer on ANSI C is 2^32 - 1 or 2147483647.
So we can use integer data type on ANSI C. So if the input is bigger, the condition of looping is false and the program will be quit.

May be, you can use long int data type but you must using decision that limit the input is not greater than 2147483647.

Thank you.

Post a Comment

Please leave a comment