给予6种硬币值,求1~100块钱平均可以用多少个硬币得到与最多的需要多少硬币得到。可以加可以减。
网上看说是完全背包问题,不过做下来也没感觉是完全背包,反正按思路来看感觉不是。方法是先加上去,然后减下来。具体看代码。
#include<stdio.h>
#include<string.h>
#include<iostream>
int a[10005] , c[10] ;
int main() {
//freopen("in.txt" , "r" , stdin) ;
int n , s , max ;
cin >> n ;
int i , j , k ;
for (k = 1 ; k <= n ; k ++) {
for (i = 1 ; i <= 6 ; i ++) {
cin >> c[i] ;
}
for (i = 1 ; i <= 10000 ; i ++) {
a[i] = 65536 ;
}
for (i = 1 ; i <= 6 ; i ++) {
a[c[i]] = 1 ;
}
for (i = 1 ; i <= 10000 ; i ++) {
for (j = 1 ; j <= 6 ; j ++) {
if (i + c[j] <= 10000) {
if (a[i] + 1 < a[i+c[j]]) {
a[i+c[j]] = a[i] + 1;
}
}
}
}
for (i = 10000 ; i >= 1 ; i --) {
for (j = 1 ; j <= 6 ; j ++) {
if (i - c[j] >= 1) {
if (a[i] + 1 < a[i-c[j]]) {
a[i-c[j]] = a[i] + 1;
}
}
}
}
s = 0 ; max = 0;
for (i = 1 ; i <= 100 ; i ++) {
s += a[i] ;
if (a[i] > max) max = a[i] ;
}
cout << s/100 << '.' << s%100 << ' ' << max << endl ;
}
return 0;
}
做完poj1252后一个高中搞信息学的好友说,这道题用spfa做一下吧,于是这份解题报告就出现了。大意是把100种硬币组合看成100个点,6种硬币值看成6种权值的边,然后用spfa做。不过这样做时间上好像没什么优化,代码量好像加长了,不过这思路,够厉害。
#include <cstdio>
#include <cstring>
#include <queue>
#include <iostream>
using namespace std ;
const int MAX = 1 << 15 ;
int f[510] = {0} ;
int c[10] = {0} ;
queue <int> q ;
bool has[510] = {0} ;
void spfa() {
for (; !q.empty() ;) q.pop() ;
q.push(250) ;
has[250] = 1 ; f[250] = 0 ;
while (!q.empty()) {
int t = q.front() ; q.pop() ;
for (int i = 1 ; i <= 6 ; i ++) {
if ((t+c[i]) < 510 && f[t]+1 < f[t+c[i]]) {
f[t+c[i]] = f[t] + 1 ;
if (!has[t+c[i]]) {q.push(t+c[i]) ; has[t+c[i]] = 1 ;}
}
if ((t-c[i]) >= 0 && f[t]+1 < f[t-c[i]]) {
f[t-c[i]] = f[t] + 1 ;
if (!has[t-c[i]]) {q.push(t-c[i]) ; has[t-c[i]] = 1 ;}
}
}
}
}
int main() {
//freopen("in.txt" , "r" , stdin) ;
int n ;
cin >> n ;
while (n --) {
for (int i = 1 ; i <= 6 ; i ++) {
cin >> c[i] ;
}
memset(has , 0 , sizeof(has)) ;
for (int i = 0 ; i <= 500 ; i ++) {
f[i] = MAX ;
}
spfa() ;
int ans = 0 , Max = 0 ;
for (int i = 251 ; i <= 350 ; i ++) {
ans += f[i] ;
if (f[i] > Max) Max = f[i] ;
}
cout << ans/100 << '.' << ans%100 << ' ' << Max << endl ;
}
return 0;
}