Cod sursa(job #1710448)

Utilizator bciobanuBogdan Ciobanu bciobanu Data 28 mai 2016 23:11:14
Problema Sate2 Scor 0
Compilator cpp Status done
Runda Arhiva ICPC Marime 1.45 kb
#include <bits/stdc++.h>

using namespace std;

constexpr int MAX_N = 3000;
constexpr int MAX_K = 4;
constexpr int NUM_ITER = 1000000;

int v[MAX_N];
int knapsack[MAX_N];
int weight[MAX_K + 1];

inline int getRandom(void) {
  static mt19937 gen(time(0));
  int x = gen();
  if (x < 0)
    x = -x;
  return x;
}

int main() {
  ifstream fin("sate2.in");
  ofstream fout("sate2.out");
  fin.tie(0);
  ios_base::sync_with_stdio(0);

  int numTests; fin >> numTests;

  while (numTests--) {
    int numItems, sumWeight, numKnapsack; fin >> numItems >> sumWeight >> numKnapsack;
    for (int i = 0; i < numItems; i += 1) {
      fin >> v[i];
      knapsack[i] = 0;
    }
    if (sumWeight % numKnapsack)
      fout << "NU\n";
    else {
      for (int i = 0; i <= numKnapsack; i += 1)
        weight[i] = 0;
      int i = 0;
      bool match;
      const int need = sumWeight / numKnapsack;
      do {
        int x = getRandom() % numItems;
        int pack = 1;
        while (weight[pack] + v[x] > need)
          pack += 1;
        weight[knapsack[x]] -= v[x];
        knapsack[x] = pack;
        weight[knapsack[x]] += v[x];
        match = 1;
        for (int j = 1; j <= numKnapsack; j += 1)
          match &= (weight[j] == need);
        match |= (++i == NUM_ITER);
      } while (!match);
      match &= (i != NUM_ITER);
      fout << (match ? "DA\n" : "NU\n");
    }
  }
  fin.close();
  fout.close();
  return 0;
}