---
title: "USACO Training Section 4.1 Beef McNuggets"
author: "blackcoffee"
date: "2010-01-26T21:37:20Z"
tags: []
categories: ["编程语言"]
slug: "usaco-training-section-4-1-beef-mcnuggets"
draft: false
lastmod: "2010-01-26T21:37:20Z"
id: 580560
url: "https://blackcoffee.iteye.com/blog/580560"
---

[英文原题](http://ace.delos.com/usacoprob2?a=4bkuxAY0Hwy&S=nuggets)  [中文题译](http://www.wzoi.org/usaco/14%5C102.asp)

 

**大意：**

 

给定N个正整数，确定由其加法不能表示的正整数的最大值。例如给若干个邮票面值，问最大不能被这些邮票组合出来的面值是多少。如果没有这样的最大值，则输出0 。

 

**分析与实现：**

 

看上去很面熟是吧，不过与之前的有所不同。

 

首先，怎样的面值组合没有最大不可表示的值？例如2,4，所有的奇数都不能表示，6,9，所有不能被3整除的都不能表示。于是规律是：N个数的最大公约数如果是1，那么一定存在这样的最大值，否则，不可表示的值可以无限大。

 

如果这样的最大值存在，怎么找？很简单，设其最小面值为k，那么如存在n使得n,n+1,...n+k-1都可以表示，则之后所有的数都可通过加贴面值为k的邮票来表示了。

 

```
/*
ID: blackco3
TASK: nuggets
LANG: C++
*/
#include <iostream>
#include <algorithm>
using namespace std;
const int _max_pack_(256) ;
int packs[_max_pack_], n_pack, unpacked[_max_pack_] ;

int gcd(int a, int b) { 
	while(a && b) 
		a %= b , b = a ? b%a : b ;  
	return a + b ;
} 

int check_bound( ) {
	int gcd_val = packs[0] ;
	for( int i=1; i<n_pack; i++ )
		gcd_val = gcd(gcd_val, packs[i] );
	return gcd_val!=1 ;
}

int main() {
    freopen("nuggets.in", "r", stdin); 
    freopen("nuggets.out","w",stdout);
	cin >> n_pack ;
	for( int i=0; i<n_pack; i++ )
		cin >> packs[i] ;
	sort( packs, packs+n_pack );
	if ( check_bound() ) {
		cout << 0 << endl ;
		return 0 ;
	}
	unpacked[0]=0 ;
	for( int i=1; i<packs[0]; i++ )
		unpacked[i]=1 ;
	int max_unpack = packs[0]-1 , max_pack = packs[n_pack-1], min_pack=packs[0] ;
	for( int cur=packs[0], cursor=-max_pack; cur <= min_pack + max_unpack ; cur++ ){
		int unpackable=1 ;	
		for( int i=0; i<n_pack; i++ ){
			if( cur>=packs[i] && !unpacked[(cur-packs[i])%max_pack] ){
				unpackable=0 ;
				break ;
			}
		}
		if( unpacked[cur%max_pack]=unpackable ) 
			max_unpack=cur ;
	}
	cout << max_unpack << endl ;	
	return 0; 
} 
```