Grid Shading Puzzle

Time limit1sMemory limit128 MB

Summary
Given per-row and per-column shaded counts for an n by n board, decide whether a valid 0/1 board exists.
Level

Medium4 of 10

Topics
Greedy, Sorting
Solved
No attempts yet

Problem

You want to solve a puzzle printed in a newspaper.

You are given a board divided into n×nn \times n unit squares. Each square may be shaded or left blank. For every row and every column you are told the exact number of squares that must be shaded.

Decide whether the board can be shaded so that all of the given per-row and per-column counts are satisfied.

Input

The first line contains the number of test cases tt (1≤t≤1001 \le t \le 100). The descriptions of the test cases follow.

The first line of each test case contains the board size nn (1≤n≤100 0001 \le n \le 100\,000). The second line contains nn integers w1,w2,…,wnw_1, w_2, \dots, w_n and the third line contains nn integers k1,k2,…,knk_1, k_2, \dots, k_n (0≤wi,ki≤n0 \le w_i, k_i \le n). Here wiw_i is the number of squares that must be shaded in row ii, and kik_i is the number of squares that must be shaded in column ii.

You may assume that the sum of nn over all test cases in a single input does not exceed 1 500 0001\,500\,000.

Output

For each test case, print a single line containing TAK if the puzzle can be solved, or NIE otherwise.

Examples2

  1. Example 1

    Input
    2
    3
    1 2 3
    3 2 1
    3
    1 3 0
    2 2 0
    
    Expected output
    TAK
    NIE
    
  2. Example 2

    Input
    2
    2
    2 0
    1 1
    2
    2 0
    2 0
    
    Expected output
    TAK
    NIE