Advertisement
mhdew

Coin Change DP

Dec 9th, 2018
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.30 KB | None | 0 0
  1. #include<stdio.h>
  2.  
  3. int main()
  4. {
  5.     int amount;
  6.     int totalcoin;
  7.     scanf("%d %d", &amount, &totalcoin);
  8.     int coin[11111];
  9.     int i;
  10.     for(i=0;i<totalcoin;i++){
  11.         scanf("%d", &coin[i]);
  12.     }
  13.  
  14.     int row=totalcoin;
  15.     int col=amount+1;
  16.     int table[row][col];
  17.     int j;
  18.     for(i=0;i<row;i++){
  19.         table[i][0]=0;
  20.     }
  21.     for(j=0;j<col;j++){
  22.         table[0][j]=j/coin[0];
  23.     }
  24.  
  25.     for(i=1;i<row;i++){
  26.         for(j=1;j<col;j++){
  27.             if(coin[i]>j){
  28.                 table[i][j]=table[i-1][j];
  29.             }
  30.             else{
  31.                 if(table[i-1][j]<table[i][j-coin[i]]+1){
  32.                     table[i][j]=table[i-1][j];
  33.                 }
  34.                 else{
  35.                     table[i][j]=table[i][j-coin[i]]+1;
  36.                 }
  37.             }
  38.         }
  39.     }
  40.  
  41.     printf("Coin needed %d\n", table[row-1][col-1]);
  42.  
  43.     i=row-1;
  44.     j=col-1;
  45.     int a[1111];
  46.     int idx=0;
  47.     while(1){
  48.         if(table[i][j]==0) break;
  49.         if(table[i][j]!=table[i-1][j]){
  50.             a[idx]=coin[i];
  51.             idx++;
  52.             j-=coin[i];
  53.         }
  54.         else{
  55.             i--;
  56.         }
  57.     }
  58.  
  59.     printf("Needed coins are: ");
  60.     for(i=idx-1;i>=0;i--){
  61.         printf("%d ", a[i]);
  62.     }
  63.     printf("\n");
  64.  
  65.     return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement