Billy investigates the question of applying greedy algorithm to different spheres of life. At the moment he is studying the application of greedy algorithm to the problem about change. There is an amount ofn coins of different face values, and the coins of each value are not limited in number. The task is to collect the sumx with the minimum amount of coins. Greedy algorithm with each its step takes the coin of the highest face value, not exceedingx. Obviously, if among the coins' face values exists the face value 1, any sumx can be collected with the help of greedy algorithm. However, greedy algorithm does not always give the optimal representation of the sum, i.e. the representation with the minimum amount of coins. For example, if there are face values {1, 3, 4} and it is asked to collect the sum6, greedy algorithm will represent the sum as 4 + 1 + 1, while the optimal representation is 3 + 3, containing one coin less. By the given set of face values find out if there exist such a sumx that greedy algorithm will collect in a non-optimal way. If such a sum exists, find out the smallest of these sums.
The first line contains an integer n (1 ≤ n ≤ 400) — the amount of the coins' face values. The second line containsn integers ai (1 ≤ ai ≤ 109), describing the face values. It is guaranteed that a1 > a2 > ... > an andan = 1.
If greedy algorithm collects any sum in an optimal way, output -1. Otherwise output the smallest sum that greedy algorithm collects in a non-optimal way.
5 25 10 5 2 1
-1
3 4 3 1
6 题意:给定n种货币,每种货币数量无限。 现在要求以最少的货币数目表示一个数S。 一种方法当然是DP求一个最优解了, 当然正 常人的做法是贪心:每次取最大的不超过当前待表示数的货币。 现在,你的任务是证明正常人的表示法不一定最优:找到最小的S,使得正常人的表示法 比理论最优解差,或说明这样的S不存在。 n ≤ 300 分析: 这是一道论文题,我自己也尝试推导了一下其中的部分结论,设M(s)为数s的最优表示,G(s)为其贪心表示,那么我们要找第一个M(s) < G(s) 的s,对于这样的s,M(s) 和 G(s) 中 一定不存在公共项(ai系数同时大于0),设M(s)中最大项为bi,G(s)中最大项为ai,则有bi < ai,且M(s) = G(x-bi) + bi,又印M(s)与G(s)不存在公共项(否则s可以更小), 所以 G(x-bi) 加上 bi项后变成 G(x) 的过程中必定发生了进位,且进位后ai = 1(两个小于ai的数相加一定小于2*ai,这表明最后s一定是大于ai小于2*ai),然后我就不会证了,设bj是M(s)中的最小项,正解中有个结论是M(s-bj)中的非零项系数一定和G(ai-1)相等,所以我们枚举ai和bj就可以了。#include<iostream> #include<string> #include<algorithm> #include<cstdlib> #include<cstdio> #include<set> #include<map> #include<vector> #include<cstring> #include<stack> #include<queue> #define INF 0x3f3f3f3f #define eps 1e-9 #define MOD 1000000007 #define MAXN 2100000007 using namespace std; typedef pair<int,int> pii; int n,ans,a[500],b[500],c[500]; int deal(int x) { int ans = 0; for(int i = 1;i <= n;i++) { b[i] = x / a[i]; ans += b[i]; x %= a[i]; if(!x) break; } return ans; } int main() { cin.sync_with_stdio(false); ans = MAXN; cin>>n; for(int i = 1;i <= n;i++) cin>>a[i]; for(int i = 1;i < n;i++) { deal(a[i]-1); for(int i = 1;i <= n;i++) c[i] = b[i]; for(int j = i+1;j <= n;j++) { int temp = 0,temp2 = 0; for(int k = 1;k <= j;k++) { temp2 += a[k]*c[k]; temp += c[k]; } temp2 += a[j],temp++; if(deal(temp2) > temp) ans = min(temp2,ans); } } if(ans == MAXN) cout<<-1<<endl; else cout<<ans<<endl; }