`
blackcoffee
  • 浏览: 55414 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

USACO Training Section 4.1 Beef McNuggets

 
阅读更多

英文原题  中文题译

 

大意:

 

给定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; 
} 

 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics