Under construction

Still being built. Things may change

Island Archipelago

Time limit10sMemory limit1024 MB

Summary
Given an n by n grid under cell toggles, count the land islands and how many have no enclosed water lake, answering each query.
Level

Hard9 of 10

Topics
Matrix, Union-find, Dynamic programming
Solved
No attempts yet

Problem

You live on an island archipelago, where the islands keep changing as the sea level rises and falls.

The archipelago is an n×nn\times n grid, where each cell is either water or land. At the start, the whole archipelago is water. Water surrounds the grid on all sides. Over time, some water cells lower to reveal land, and some land cells sink back into water.

Two land cells are edgewise-connected if you can walk between them by moving left, right, up, or down through land cells only. An island is a maximal edgewise-connected group of land cells. Islands can also sit inside other islands. For example, an island can enclose a lake that holds another island.

One concern of the citizens is whether an island encloses a freshwater lake. An island has a freshwater lake if some closed loop of its land cells, formed by steps up, down, left, and right, encircles at least one water cell. In the diagram below, # is land and blank cells are water. There are five islands (two on the left, one in the middle, and two on the right). Only the outer island on the right contains a freshwater lake.

           #####
           #   #
##   ####  # # #
# #  ## #  #  ##
 ##  ###   #####

The citizens want to know the total number of islands and how many of them do not contain a freshwater lake.

Input

The first line contains two space-separated integers nn and mm (1≤n≤1 500,1≤m≤5⋅104)(1 \leq n \leq 1\,500, 1 \leq m \leq 5\cdot 10^4), the size of the grid and the number of queries. The leftmost column has index c=1c = 1, and the topmost row has index r=1r = 1.

Each of the next mm lines begins with either ! or ?.

A line that begins with ! is followed by two space-separated integers rr and cc (1≤r,c≤n)(1 \leq r,c\leq n). The cell at (r,c)(r,c) has changed from water to land, or from land to water.

A line that begins with ? has no other input. It asks for the current state of the archipelago.

Output

For each ? query, print one line with two space-separated integers. The first is the current number of islands. The second is the number of those islands that do not contain a freshwater lake.

Examples1

  1. Example 1

    Input
    3 18
    ?
    ! 1 1
    ! 1 2
    ! 1 3
    ! 3 1
    ?
    ! 2 1
    ?
    ! 3 2
    ! 3 3
    ! 2 3
    ?
    ! 3 3
    ?
    ! 1 1
    ?
    ! 2 2
    ?
    
    Expected output
    0 0
    2 2
    1 1
    1 0
    1 1
    2 2
    1 1