POJ 3492 Knapsack II

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值