Railway Siding
Time limit1sMemory limit128 MB
Assign each arriving car to one of two stack-like sidetracks so all cars leave in increasing order.
- Level
Medium7 of 10
- Topics
- Stack, Greedy, Implementation
- Solved
- No attempts yet
Problem
A railway siding has two dead-end sidetracks, numbered and . Cars enter the siding from track A and leave it on track B.

There are cars on track A, numbered to . They enter the siding in the order . We want them to leave on track B in the order .
Each car is moved once from track A onto sidetrack or , and later moved once from that sidetrack onto track B. A sidetrack behaves like a stack: the car placed on it most recently is the first one that can be removed. The sidetracks are long enough to hold any number of cars, so their capacity is never a concern.
Cars leave track A strictly in the order , but you may move a car from a sidetrack to track B at any moment, including between the arrivals of later cars. Decide whether the cars can be reordered into on track B, and if so, choose which sidetrack each car is placed on.
Input
The first line contains one integer (), the number of cars.
The second line contains , a permutation of , separated by single spaces.
Output
If the cars cannot be rearranged into the order on track B, print a single line containing the word NIE (meaning it is impossible).
Otherwise, print TAK (meaning it is possible) on the first line. On the second line print integers separated by single spaces: the -th integer is the sidetrack ( or ) onto which car is moved.
If more than one valid assignment exists, print the lexicographically smallest one: compare two assignment sequences position by position from left to right, and prefer the one with the smaller sidetrack number at the first position where they differ.
Hint
Take the sequence . Move car onto sidetrack and immediately move it to track B. Move car onto sidetrack , then car onto sidetrack . Finally move car onto sidetrack ; now cars and then leave sidetrack onto track B, followed by car from sidetrack . Track B receives in order, and the sidetrack choices are .