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
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Scanner;

/**
 * Created by stawicad on 2016-11-26.
 */
public class sze {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        PriorityQueue<int[]> tasks = new PriorityQueue<>(new Comparator<int[]>() {
            @Override
            public int compare(final int[] o1, final int[] o2) {
                int compare = Integer.compare(o1[0], o2[0]);
                return compare != 0 ? compare : Integer.compare(o1[1] - o1[0] - o1[2], o2[1] - o2[0] - o2[2]);
            }
        });
        for (int i = 0; i < n; i++) {
            tasks.offer(new int[]{sc.nextInt(), sc.nextInt(), sc.nextInt()});
        }
        System.out.println(scheduled(tasks, m) ? "TAK" : "NIE");
    }

    private static boolean scheduled(PriorityQueue<int[]> tasks, int m) {
        List<int[]> reschedule = new ArrayList<>(100);
        while (!tasks.isEmpty()) {
            if(tasks.size() <= m) {
                for (int[] task : tasks) {
                    if(task[2] > task[1] - task[0]) return false;
                }
                return true;
            }
            int[] head = tasks.poll();
            for (int i = 0; !tasks.isEmpty() && tasks.peek()[0] == head[0]; i++) {
                int[] polled = tasks.poll();
                if(polled[0] == polled[1]) return false;
                polled[0]++;
                if(i < m - 1) polled[2]--;
                if(polled[2] > 0) reschedule.add(polled);
            }

            head[0]++;
            head[2]--;
            if(head[2] > 0) tasks.offer(head);
            tasks.addAll(reschedule);
            reschedule.clear();
        }
        return true;
    }
}