Cod sursa(job #1710015)

Utilizator TeamFIIHUAIC FIICoders TeamFIIH Data 28 mai 2016 14:46:50
Problema Sate2 Scor 0
Compilator cpp Status done
Runda ONIS 2016 - Runda - 2 - ACM ICPC Romanian Programming Contest Marime 2.1 kb
#include <fstream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <functional>
#include <utility>
#include <cstdio>

using namespace std;

int main()
{
    //ios_base::sync_with_stdio(false);

    freopen("sate2.in", "r", stdin);
    freopen("sate2.out", "w", stdout);

    int t;
    scanf("%d", &t);

    while (t--){

        int n, m, k;
        multiset<int> b[4];
        int sums[4] = {0};

        scanf("%d %d %d",&n, &m, &k);

        for (int i = 0; i < n; ++i){
            int x;
            scanf("%d", &x);

            b[i % k].insert(x);
            sums[i % k] += x;
        }
        if (m % k) {
            printf("NU\n");
            continue;
        }

        int target = m/k;
        int ok = 0;

        for (int zz = 0; zz < 7*n; ++zz){
            int hi = -1, low = -1;

            ok = 1;
            for (int i = 0; i < k; ++i){
                if (sums[i] != target) ok = 0;
            }
            if (ok == 1) break;

            hi = rand() % k;
            do{
                low = rand() % k;
            }while (low == hi);

            if (sums[low] > sums[hi]) swap(low, hi);
            if (sums[low] == target || sums[hi] == target){
                continue;
            }

            int dif = sums[hi] - target;
            multiset<int> :: iterator elem = b[hi].lower_bound(dif);
            if (elem == b[hi].end() && elem != b[hi].begin()) --elem;

            int val = *elem;

            sums[low] += val;
            sums[hi] -= val;

            int cnt = b[hi].count(val) - 1;

            b[low].insert(val);
            b[hi].erase(val);

            for (int i = 0; i < cnt; ++i){
                b[hi].insert(val);
            }

            /*
            for (int i = 0; i < k; ++i){
                printf("%d ", sums[i]);
            }
            printf("\n");
            */
        }

        if (ok) printf("DA\n");
        else printf("NU\n");
    }



    return 0;
}