International Cow Lineup Photo Contest
Time limit2sMemory limit512 MB
Given a 0/1 array and up to 1e5 adjacent swaps, after each swap report the longest subarray with equal numbers of 0s and 1s.
- Level
Hard9 of 10
- Topics
- Segment tree, Prefix sum, Array, Implementation
- Solved
- No attempts yet
Problem
Hyeonuk found an invitation to the finals of the International Cow Lineup Photo Contest in a treasure chest. The winner of this contest, which draws the attention of dairy farmers around the world, has been a farmer named John from USACO Farm for 20 years straight, without missing a single contest since it began. Hyeonuk wants to be the first Korean winner, so he decides to take a great photo of the cows he raises and enter.
The exact judging criteria are not known, but rumor says that the number of cows and the number of bulls in the photo must be equal, and that the more animals appear in the photo, the higher the score. Hyeonuk thought about picking a few of his cows and taking a photo that fits the criteria, but the animals left out would be disappointed, so he plans to photograph all of them and then trim the photo vertically on the left and right before submitting it.
Hyeonuk is busy enough just taking the photos, so he asks you to do the trimming. That is, you must trim the given photo so that it fits the judging criteria: the number of cows and the number of bulls are equal, and the number of animals is as large as possible.
If the cows stood still, taking photos would be relatively easy, but they lack patience, so while lined up they do not stand still and now and then two adjacent cows swap places. However, multiple pairs never swap at the same time. Hyeonuk takes a new photo every time the cows swap places.
Given the initial lineup and information about how the cows moved between photos, write a program that for each photo computes the length of the longest contiguous segment in which the number of cows and the number of bulls are equal.
Input
The first line gives the number of cows and the number of photos .
The second line gives numbers. Each number is or ; means a cow and means a bull.
The third line gives numbers , , ..., . Each means that the -th cow and the -th cow swapped places.
Output
On the first line, output the length of the longest contiguous segment in the initial lineup in which the number of cows and the number of bulls are equal.
On each of the following lines, output the length of the longest contiguous segment in which the number of cows and the number of bulls are equal after the cows swap places. If no segment can be trimmed to make the numbers of cows and bulls equal, output for that photo.