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
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
#include <algorithm>
#include <vector>
#include <iostream>

using namespace std;

int count_islands(const std::vector<int> &nums) {
    bool onIsland = false;
    int cnt = 0;
    for (const int num: nums) {
        if (num != 0) {
            if (!onIsland) {
                onIsland = true;
                cnt += 1;
            }
        } else {
            onIsland = false;
        }
    }
    return cnt;
}

vector<int> extract_island(const std::vector<int> &nums) {
    vector<int> result;
    ranges::copy_if(nums, back_inserter(result), [](const int num) { return num != 0; });
    return result;
}

bool check(std::vector<int> &island) {
    vector nums(island.begin(), island.end());
    while (nums.size() > 2) {
        auto a = nums.back();
        nums.pop_back();
        auto b = nums.back();
        nums.pop_back();
        if (b >= a) {
            nums.push_back(b - a + 1);
        } else {
            return false;
        }
    }
    if (nums.size() == 1) {
        return nums[0] == 1;
    }
    if (nums.size() == 2) {
        auto a = nums[nums.size() - 1];
        auto b = nums[nums.size() - 2];
        return a - b == 0 || a - b == 1;
    }
    throw runtime_error("Should never happen");
}

vector<int> reduce_right(const std::vector<int> &nums) {
    vector result(nums.rbegin(), nums.rend());
    const auto n = result.size();
    for (int i = 0; i + 2 <= n; i++) {
        const auto delta = min(result[i], result[i + 1]) - 1;
        result[i] = result[i] - delta;
        result[i + 1] = result[i + 1] - delta;
    }
    return result;
}

void readAndSolveTestCase() {
    int a, n;
    cin >> n;
    vector<int> nums;
    for (int i = 0; i < n; i++) {
        cin >> a;
        nums.push_back(a);
    }
    const auto islands_count = count_islands(nums);
    if (islands_count > 1) {
        cout << "NIE" << endl;
        return;
    }

    auto island = extract_island(nums);
    if (island.size() == 1) {
        cout << (island[0] == 1 ? "TAK" : "NIE") << endl;
        return;
    }

    if (check(island)) {
        cout << "TAK" << endl;
        return;
    }
    island[island.size() - 2] -= 1;

    if (check(island)) {
        cout << "TAK" << endl;
    } else {
        cout << "NIE" << endl;
    }
}

int main() {
    ios_base::sync_with_stdio(false);
    int t;
    cin >> t;
    while (t--) {
        readAndSolveTestCase();
    }

    return 0;
}