1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <iostream>
#include <algorithm>

long t, n;
const long MAXN = 100000;
const long MAXT = 1000000;
long l[MAXN];
long a[MAXN];
long b[MAXN];

bool solve_one()
{
    long long total_energy_in = 0;
    long long total_energy_out = 0;

    std::pair<long, long> histogram_in[MAXN]; // temperature, litres
    std::pair<long, long> histogram_out[MAXN]; // temperature, litres

    for (long i=0; i<n; ++i){
        total_energy_in += l[i] * a[i];
        total_energy_out += l[i] * b[i];
        histogram_in[i] = {a[i], l[i]};
        histogram_out[i] = {b[i], l[i]};
    }
    if (total_energy_in != total_energy_out){
        return false;
    }

    long long credit_litres = 0;
    long long credit_energy = 0;
    long long target_litres = 0;
    long long target_energy = 0;

    std::sort(histogram_in, histogram_in+n);
    std::sort(histogram_out, histogram_out+n);

    long current_temperature = 0;
    long pointer_in = 0;
    long pointer_out = 0;

    while (pointer_in < n || pointer_out < n)
    {
        long next_temperature = MAXT + 100;
        if (pointer_in < n)
        {
            next_temperature = std::min(next_temperature, histogram_in[pointer_in].first);
        }
        if (pointer_out < n)
        {
            next_temperature = std::min(next_temperature, histogram_out[pointer_out].first);
        }
        long step = next_temperature - current_temperature;
        current_temperature = next_temperature;

        credit_energy += step*credit_litres;
        target_energy += step*target_litres;

        if (pointer_in < n && next_temperature == histogram_in[pointer_in].first)
        {
            credit_litres += histogram_in[pointer_in].second;
            ++pointer_in;
        }
        if (pointer_out < n && next_temperature == histogram_out[pointer_out].first)
        {
            target_litres += histogram_out[pointer_out].second;
            ++pointer_out;
        }

        if (target_energy > credit_energy)
        {
            return false;
        }
    }
    return true;
}

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin >> t;
    while (t--)
    {
        std::cin >> n;
        for (long i=0; i < n; ++i)
        {
            std::cin >> l[i] >> a[i] >> b[i];
        }
        bool possible = solve_one();
        std::cout << (possible ? "TAK" : "NIE") << std::endl;
    }
}