Пожалуйста, подпишитесь на официальный канал Codeforces в Telegram по ссылке https://t.me/codeforces_official. ×

Блог пользователя steelarm

Автор steelarm, история, 7 лет назад, По-английски

The problem

I am trying out the following approach:

1.I sort the array of weights in decreasing order and "put" the largest weight in one group.

2.Then I keep adding weights to the other group until it becomes larger.

3.Then I start adding apples to the first group until this is one is larger and again start putting apples in the other group and keep on going like this until i reach the end of the array.

4.And then I print the difference between the total weights of the two groups.

My solution gives the correct answer with the sample test cases and a few others too but I am getting a WA, so can anyone suggest something I can do to correct my code. Code:

#include <bits/stdc++.h>
using namespace std;

#define B begin()
#define E end()
#define I iterator
using pii = pair < int , int >;
using vi = vector < int >;
using llu = unsigned long long int;
using ll = long long int;


//ofstream cout ("op.txt");
//ifstream fin("inp.in");
int main ()
{
    ll n;
    cin >> n;
    vector <ll> vec(n);
    ll val;
    for ( int i = 0 ; i < n ; i ++ ){
        cin >> val;
        vec[i] = val;
    }
    sort ( vec.B , vec.E , greater<ll>() );
    ll ansa = 0 , ansb = 0 ;
    ansa = vec[0];
    for ( int i = 1; i < n ; i++ ){
        if ( ansb < ansa )
            ansb += vec[i];
        else
            ansa += vec[i];
    }
    cout << max( ansa , ansb ) - min( ansa , ansb );
    return 0;
}



Any and all help is appreciated

  • Проголосовать: нравится
  • +4
  • Проголосовать: не нравится

»
7 лет назад, скрыть # |
← Rev. 2  
Проголосовать: нравится 0 Проголосовать: не нравится

Try with

5 5 5 7 8

»
6 лет назад, скрыть # |
← Rev. 2  
Проголосовать: нравится 0 Проголосовать: не нравится

As N is maximum 20 you can take all possible combinations of elements and put them in one group and put others in another group and check their difference. Maximum complexity will be 2^20 which is acceptable. Something like this:-

for (ll i = 0; i < pow(2, n); i++) { ll sum1 = 0, sum2 = 0; for (ll j = 0; j < n ; j++) { if (i & 1 << j) sum1 += a[j]; else sum2 += a[j]; } min1 = min(min1, abs(sum1 - sum2)); }

Hope it helps!