POJ 2818 : Making Change - dfs
来源:互联网 发布:淘宝买家秀福利的店铺 编辑:程序博客网 时间:2024/05/18 01:22
(寒假马拉松第一场 P题)
题意:
商店有面值为25分、10分、5分、1分的硬币,给出各硬币的数量和要找给顾客的钱数,问怎么使找给顾客的总的硬币数最少。
分析:
DFS,最暴力的方法是枚举所有的情况;——POJ 此题数据较弱,暴搜即可AC
再加上优化:已经满足钱数 或 已经超过钱数,则不再搜索,——当数据量大时则须优化,以免TLE。
#include<iostream>#include<cstdio>using namespace std;int cnt,w[5],ans[5],num[5],tot,m;int c[]={25,10,5,1};void dfs(int x){int i,sum,n;if(x>3){sum=0,n=0;for(i=0;i<4;i++){sum+=c[i]*num[i];n+=num[i];}if(sum==tot){if(n<m){for(i=0;i<4;i++)ans[i]=num[i];m=n;}cnt++;}}else{for(i=0;i<=w[x];i++){num[x]=i;dfs(x+1);}}}int main(){while(~scanf("%d%d%d%d%d",&w[0],&w[1],&w[2],&w[3],&tot)&&(w[0]+w[1]+w[2]+w[3]+tot)){m=w[0]+w[1]+w[2]+w[3]+1;cnt=0;dfs(0);if(cnt==0)printf("Cannot dispense the desired amount.\n");elseprintf("Dispense %d quarters, %d dimes, %d nickels, and %d pennies.\n",ans[0],ans[1],ans[2],ans[3]);}return 0;}
优化后:
#include<stdio.h>int m[5], cnt, res[5], num[5], C, MIN;int c[] = {25, 10, 5, 1};void dfs(int d, int tot){ int i, j, n, temp; if(d > 3) { return; } else { for(i = 0; i <= m[d]; i ++) { temp = tot - i*c[d]; if(temp < 0) break; else if(temp == 0) { cnt++; for(j = n = 0; j < d; j ++) n += num[j]; if(n+i < MIN) { for(j = 0; j < d; j ++) { res[j] = num[j]; } res[d] = i; for(j = d+1; j < 4; j ++) { res[j] = 0; } MIN = n+i; } break; } else { num[d] = i; dfs(d+1, temp); } } }}int main(){ while(scanf("%d%d%d%d%d", &m[0], &m[1], &m[2], &m[3], &C), m[0]||m[1]||m[2]||m[3]||C) { MIN = m[0]+m[1]+m[2]+m[3]+1; cnt = 0; dfs(0, C); if(cnt == 0) printf("Cannot dispense the desired amount.\n"); else printf("Dispense %d quarters, %d dimes, %d nickels, and %d pennies.\n", res[0], res[1], res[2], res[3]); } return 0;}
- POJ 2818 : Making Change - dfs
- TOJ 2273 POJ 2818 Making Change DFS C语言
- poj 2818 Making Change 枚举
- DFS 2273. Making Change
- TOJ2273 Making Change ----DFS
- Making Change
- fjnu 1195 Making Change
- Change-making problem
- toj2273 Making Change
- poj2818 - Making Change
- Making Change UVA, 166
- uva 166 Making Change
- uva 166Making Change
- Python checkio "Making Change"解决方案
- HDU_2069 Coin Change(dfs)
- POJ 3666 Making the Grade
- POJ 3666 Making the Grade
- POJ 3666 Making the Grade
- ZOJ 1586 : QS Network - prim算法解决最小生成树问题
- ZOJ 2588 : Burning Bridges - 无向图求割边(裸)
- POJ 1419 : Graph Coloring - 最大团(裸)
- POJ 2800 : Joseph\'s Problem (须仔细分析)
- POJ 2680 / ZOJ 2584 : Computer Transformation - 打表+找规律+高精度 / java大数
- POJ 2818 : Making Change - dfs
- POJ 2796 : Feel Good - 区间运算最值
- POJ 2973 : Scrabble - 字符串
- POJ 2756 : Autumn is a Genius - java大数
- POJ 2677 / ZOJ 2581 : Tour - DP
- POJ 1835 : 宇航员 - 模拟,三维向量旋转
- POJ 2714 : Random Walk - 贪心
- POJ 3177 / POJ 3352 : Redundant Paths / Road Construction - 边双连通分量,缩点
- #include<list>类的用法