Coloring the Table

Interview

Time limit2sMemory limit256 MB

Summary
Count colorings of an n by m grid, red or blue, where every 2 by 2 block has an odd number of red cells, respecting k fixed cells.
Level

Medium7 of 10

Topics
Math, Combinatorics, Union-find, Implementation
Solved
No attempts yet

Problem

Sam and his younger sister Sara want to color every cell of an n×mn \times m table either red or blue. Because of their personal belief, they want every 2×22 \times 2 square block of the table to contain an odd number of red cells (that is, exactly 1 or 3). For example, such a valid coloring also exists for a 3×53 \times 5 table.

Last night, however, someone painted some of the cells red and some blue in advance. Keeping the colors of those already-painted cells, Sam and Sara want to know whether they can color the remaining cells so that every 2×22 \times 2 square block contains an odd number of red cells. If it is possible, they also want to know how many different ways there are to do so.

Input

The first line contains three integers nn, mm, and kk: the number of rows, the number of columns, and the number of pre-colored cells, respectively. Each of the next kk lines describes one pre-colored cell with three integers xix_i, yiy_i, and cic_i, where xix_i and yiy_i are the row and column of the cell and cic_i is its color: ci=1c_i = 1 if it is red and ci=0c_i = 0 if it is blue. The positions of the kk pre-colored cells are all distinct.

  • 2≤n,m≤1052 \le n, m \le 10^5
  • 0≤k≤1050 \le k \le 10^5
  • 1≤xi≤n1 \le x_i \le n
  • 1≤yi≤m1 \le y_i \le m
  • ci∈{0,1}c_i \in \{0, 1\}

Output

Let WW be the number of ways to color the table so that the condition holds. Print WW modulo 10910^9 on a single line.

Examples3

  1. Example 1

    Input
    3 4 3
    2 2 1
    1 2 0
    2 3 1
    
    Expected output
    8
    
  2. Example 2

    Input
    2 2 0
    
    Expected output
    8
    
  3. Example 3

    Input
    2 2 4
    1 1 1
    1 2 0
    2 1 0
    2 2 0
    
    Expected output
    1