First, solve the problem. Then, write the code. ” - John Johnson

It's not at all important to get it right the first time. It's vitally important to get it right the last time. ” - Andrew Hunt and David Thomas

Sunday, September 21, 2014

357 - Let Me Count The Ways(Knapsack Algorithm)

Author : Jisan
Programming language : Java 
Difficulty : Easy
Status : Accepted
Problem number : UVA-357
 http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=24&problem=293&mosmsg=Submission+received+with+ID+14243094

Code:

import java.util.*;
public class LetMeCountTheWays {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in=new Scanner(System.in);
        long[] ways=new long[40000];
        int[] coin={50,25,10,5,1};
       
        int types=5;
        int i,j,change,taken;
       
        ways[0]=1;
        for(i=0;i<types;i++){
            taken=coin[i];
            for(j=taken;j<=30000;j++){
                ways[j]+=ways[j-taken];
            }
        }
       
       
        while(in.hasNextInt()){
             change=in.nextInt();           
              if(ways[change] == 1){
                System.out.println("There is only "+ways[change]+" way to produce "+change+" cents change.");
              }else{
                System.out.println("There are "+ways[change]+" ways to produce "+change+" cents change.");
              }
        }

    }

}

No comments:

Post a Comment