参考:http://blog.youkuaiyun.com/rlt1296/article/details/52573608
Description
Lambert wants to carry several kinds of items with a knapsack. Items of each kind have integral size and infinite supply. The knapsack also has an integral capacity. Lambert discovers an interesting fact that for any sufficiently large knapsack, its capacity can always be fulfilled. For example, for any knapsack of capacity at least 24, it can always be completely filled using items of sizes 4, 9 and 13. Given n kinds of items, what is the capacity of the largest knapsack that cannot be fulfilled?
Input
The input contains multiple test cases. Each test case begins with a line containing n (1 ≤ n ≤ 500). Then comes a line containing the sizes of different kinds of items, each not exceeding 5000. The input ends once EOF is met.
Output
For each test case, output one line containing the capacity of the largest knapsack that cannot be fulfilled. If there is not such largest knapsack, output “INF”.
Sample Input
3
4 9 13
2
2 4
Sample Output
23
INF
题意:N种长度的小木条最长不能够拼成多长的木条。
把木条按照长度最短的木条的长度分为几个同余类,我们只需要求出每个同余类内能够拼成的最短的木条,那么这个同余类内比他长的木条都可以通过添加最短的那根木条拼成。
可以把同余类看成节点,从每个 x 到 (x+Ai) mod L 连一条长度为 Ai 的边(Ai为每根木条长度,L为最短木条长度),然后以0为起点求单源最短路。
在所有点到0号点的最短路中取最大值记为T,那么最长不能够拼成的木条就是T-L。
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
queue<int>q;
int n,ans,a[505],dis[5005];
bool vis[5005];
bool pd()
{
for(int i=1;i<=n-1;i++)
if(a[i]%a[0]!=0)
return 0;
return 1;
}
int main()
{
while(scanf("%d",&n)==1)
{
for(int i=0;i<=n-1;++i)
scanf("%d",&a[i]);
sort(a,a+n);
if(pd())
{
printf("INF\n");
continue;
}
ans=0;
memset(dis,0x3f,sizeof(dis));
memset(vis,0,sizeof(vis));
dis[0]=0;
q.push(0);
vis[0]=1;
while(!q.empty())
{
int u=q.front();
for(int i=1;i<=n-1;i++)
if(dis[(u+a[i])%a[0]]>dis[u]+a[i])
{
dis[(u+a[i])%a[0]]=dis[u]+a[i];
if(!vis[(u+a[i])%a[0]])
{
vis[(u+a[i])%a[0]]=1;
q.push((u+a[i])%a[0]);
}
}
q.pop();
vis[u]=0;
}
for(int i=1;i<=a[0]-1;++i)
ans=max(ans,dis[i]);
printf("%d\n",ans-a[0]);
}
return 0;
}
本文介绍了一个背包问题的求解方法,对于给定不同大小的物品种类,如何确定无法填满的最大背包容量。采用图论中的最短路径算法解决该问题,并提供了一段C++代码实现。
1589

被折叠的 条评论
为什么被折叠?



