Ensure that you are logged in and have the required permissions to access the test.

Cycle string

4

2 votes
Dynamic Programming, Algorithms, Approved, Easy-Medium
Problem

Given two cyclic sequences A and B each of length n, consisting of 0 and 1. In cyclic sequence ai+1 comes after ai and a0 comes after an1. In a single turn you can flip three consecutive elements: ai, a(i+1)modn and a(i+2)modn. Flipping element is altering its value: if it is 0, it becomes 1, and vice versa. What is the minimum number of turns you need to make to obtain sequence B from A?

Input format

First line of input contains single integer n (3n2105) — the length of A and B.

The second line of input contains n integers ai (0ai1) — sequence A.

The third line of input contains n integers bi (0bi1) — sequence B.

Output format

Print single integer — number of operations if it is possible to obtain B from A. Otherwise print "Impossible" (without quotes).

Sample Input
4
0 0 1 1
1 0 1 1
Sample Output
3
Time Limit: 1
Memory Limit: 512
Source Limit:
Explanation

Sequence of turns in the example is

  • (0,0,1,1) - sequence A
  • (1,1,1,0) - 1, 2 and 4 are flipped
  • (0,0,0,0) - 1, 2 and 3 are flipped
  • (1,0,1,1) - 1, 3 and 4 are flipped, sequence B
Editor Image

?