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
/** Kajetan Lewandowski **/

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

long long sp,sk,buf,mk=-1,mik=1e9+7,mka=-1,mika=1e9+7,me;
bool dead=0;
pair<long long,long long>a[100005];
pair<long long,long long>b[100005];

int main() {
    int t,n;
    scanf("%d",&t);
    while(t--){
        sp=0; sk=0; buf=0; mk=-1; mik=1e9+7; mka=-1; mika=1e9+7; dead=0; me=0;
        scanf("%d",&n);
        for(int i=0; i<n; ++i) {
            scanf("%lld%lld%lld",&a[i].second,&a[i].first,&b[i].first);
            b[i].second=a[i].second;
            mika=min(mika,b[i].first);
            mka=max(mka,b[i].first);
            mik=min(mik,a[i].first);
            mk=max(mk,a[i].first);
            sp+=(a[i].first*a[i].second); sk+=(b[i].first*b[i].second);
        }
        if(sp!=sk || mka>mk || mika<mik){
            printf("NIE\n");
            continue;
        }
        sort(a,a+n,greater<pair<int,int > >());
        sort(b,b+n,greater<pair<int,int > >());
        /*for(int i=0; i<n; ++i){
            cout<<a[i].first<<"("<<a[i].second<<") "<<b[i].first<<"("<<b[i].second<<")\n";
        }*/
        int fk=0;
        long long ek,mk;
        for(int i=0; i<n; ++i){
            if(fk>=n){
                printf("NIE\n");
                dead=1;
                break;
            }
                //cout<<"r"<<buf<<" "<<fk<<endl;
            ek=0; mk=0;
            while(mk+a[fk].second<=b[i].second){
                    //cout<<"l"<<a[fk].second<<" "<<b[i].second<<i<<endl;
                mk+=a[fk].second;
                ek+=(a[fk].second*a[fk].first);
                ++fk;
                if(fk==n)break;
            }
            if(mk<b[i].second && fk<n){
                long long lll = b[i].second-mk;
                mk+=(b[i].second-mk);
                a[fk].second-=lll;
                ek+=(lll*a[fk].first);
            }else if(mk<b[i].second){
                printf("NIE\n");
                dead=1;
                break;
            }
            if(ek>b[i].first*b[i].second){
                buf+=(ek-b[i].first*b[i].second);
            } else if(ek<b[i].first*b[i].second){
                buf-=(b[i].first*b[i].second-ek);
            }
            if(buf<0){
                printf("NIE\n");
                dead=1;
                break;
            }
        }
        if(dead)continue;
        if(buf>=0)printf("TAK\n");
    }

}