📄 toj_2821_2.cpp
字号:
/*2821. Grouping Problem Time Limit: 1.0 Seconds Memory Limit: 65536KTotal Runs: 288 Accepted Runs: 157This is a short problem. However, short doesn't mean easy. You should think about it carefully.N students are going to play the game of "Tug of War", which both you and me are familiar with. N people must be divided into two teams, and each person must be on one team or the other. For the reason of being fair, the difference of total weights of the two teams should be as nearly equal as possible.InputThere are multiple test cases. The first line of each test case contains a single integer N (2 ≤ N ≤ 15). It is followed by a line with N integers indicating the weight of the N students. The weight is at least 80, and at most 400.A line with a single zero indicates the end of the input.OutputFor each case, just print a line with a non-negative integer D, which is the smallest difference of the total weights of the two teams.Sample Input38510020051002002051002050Sample Output150Problem Setter: VeniceSource: TJU Programming Contest 2007*/#include<cstdio>#include<cstdlib>#include<cstring>int main(){ int position , n , i , j , choice [ 20 ] , weight[ 20 ] , totalWeight , partWeight , diff , min;// freopen( "toj_2821_in.txt" , "r" , stdin ); while ( scanf( "%d" , &n ) && n ) { for( totalWeight = 0 , i = 0; i < n; i++ ){ scanf( "%d" , &weight[ i ] ); totalWeight+= weight[ i ] ; } memset( choice , 0 , sizeof( int ) * n ); position = 0; partWeight = 0; min = 0x7fffffff; while ( position < n ) { // for( partWeight = 0 , i = 0; i < n; i++ ) // partWeight += choice[ i ] * weight[ i ]; diff = abs( totalWeight - 2 * partWeight ); if ( diff < min ) min = diff; choice[ 0 ]++; position = 0; while ( choice[ position ] > 1 ){ partWeight -= weight[ position ]; choice[ position ] = 0; position++; choice[ position ] ++; partWeight += weight[ position ]; } } printf( "%d\n" , min ); } return 0;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -