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
92
93
94
#include <cstdio>
#include <algorithm>
using namespace std;

int des[50010];
int act[50010];
int h[50010];
int l[50010];
int where[50010];
int tmp[50010];
int t, n, w, x1, x2, y1_, y2;

struct cuscmp {
  bool operator()(int a, int b) {
    return l[a] < l[b];
  }
};

inline int mabs(int x) {
  return x > 0 ? x : -x;
}

int przemiel(int t[]) {
  for (int i = 0; i < n; i++) {
    scanf("%d%d%d%d",&x1,&y1_,&x2,&y2);
    h[i] = mabs(y1_ - y2);
    l[i] = min(x1, x2);
    t[i] = i;
  }
  sort(t, t+n, cuscmp());
}

bool mergesort(int a, int b) {
  if (b == a+1) {
    return true;
  }

  int c = (a+b)/2;

  if (!mergesort(a, c) || !mergesort(c, b))
    return false; 

  int m = 0, x=a, y=c, pos=a;

  while (x < c || y < b) {
    if (x == c) {
      tmp[pos++] = act[y];
      y++;
    }
    else if (y == b) {
      tmp[pos++] = act[x];
      if (h[act[x]] + m > w)
        return false;
      x++;
    }
    else 
    {
      if (where[act[x]] < where[act[y]]) {
        if (h[act[x]] + m > w)
          return false;
        tmp[pos++] = act[x];
        x++;
      }
      else
      {
        tmp[pos++] = act[y];
        m = m > h[act[y]] ? m : h[act[y]];
        y++;
      }
    }
  }

  for (int i = a; i < b; i++)
    act[i] = tmp[i];

  return true;
}

int main() {
  scanf("%d",&t);
  while (t--) {
    scanf("%d%d",&n,&w);
    przemiel(act);
    przemiel(des);

    for (int i = 0; i < n; i++)
      where[des[i]] = i;

    if (mergesort(0, n))
      printf("TAK\n");
    else
      printf("NIE\n");
  }
}