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
#include <iostream>
#include <map>
#include <algorithm>

using uint64 = std::uint64_t;
using int64 = std::int64_t;

bool check(int64 rows) {
    int64 l, a, b;
    int64 begin_temp_sum = 0;
    int64 end_temp_sum = 0;
    std::map<int, int64> tab;
    for(int row = 0; row < rows; row++){
        std::cin >> l >> a >> b;
        tab[a] += l;
        tab[b] -= l;
        begin_temp_sum += l * a;
        end_temp_sum += l * b;
    }
    if(begin_temp_sum != end_temp_sum)
        return false;

    while(true){
        auto s = tab.size();
        if(s < 3)
            return true;
        auto first = tab.begin();
        if(first->second == 0) {
            tab.erase(first);
            continue;
        }

        auto last = std::prev(tab.end());

        if(last->second == 0) {
            tab.erase(last);
            continue;
        }

        if(last->second < 0 && first->second < 0)
            return false;

        if(first->second > 0){
            while(last->second > 0) {
                last = prev(last);
            }
            last->second += first->second;
            tab[last->first -1] -= first->second;
            tab[first->first + 1] += first->second;
            first->second = 0;
        } else {
            while(first->second > 0) {
                first = next(first);
            }
            first->second += last->second;
            tab[last->first -1] += last->second;
            tab[first->first + 1] -= last->second;
            last->second = 0;
        }
    }
}

int main()
{
    std::ios_base::sync_with_stdio(false);
    int64 n, rows;
    std::cin >> n;
    for(int i = 0; i < n; i++) {
        std::cin >> rows;
        auto ret = check(rows);
        if(ret)
            std::cout << "TAK\n";
        else
            std::cout << "NIE\n";
    }
    return 0;
}