您的位置:首页 > 其它

UVa 10465 - Homer Simpson

2013-05-03 13:53 183 查看
背包问题,要求出重量恰好是t的最大价值 (每个物品的价值是1)。此题分为恰能达到重量t和不能达到重量t两种情况。再求背包的过程中要注意。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>

using namespace std;

int m, n, t, opt[10005], V[3];

int main ( ) {
while ( scanf ( "%d%d%d", &m, &n, &t ) == 3 ) {
V[1] = m, V[2] = n;
memset ( opt, -1, sizeof ( opt ) );
opt[0] = 0;
for ( int i = 1; i <= 2; ++i )
for ( int j = V[i]; j <= t; ++j )
if ( opt[j - V[i]] != -1 ) opt[j] = max ( opt[j], opt[j - V[i]] + 1 );
int tmp = 0;
for ( int i = t; i >= 0; --i ) {
if ( opt[i] != -1 ) break;
++tmp;
}
printf ( "%d", opt[t - tmp] );
if ( tmp != 0 ) printf ( " %d", tmp );
printf ( "\n" );
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: