C++#include <iostream>
#include <vector>
#include <tuple>
using namespace std;
const int MOD = 998244353;
long long mod_pow(long long base, long long exp, long long mod) {
long long result = 1;
base %= mod;
while (exp > 0) {
if (exp & 1) {
result = (result * base) % mod;
}
base = (base * base) % mod;
exp >>= 1;
}
return result;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m, k;
cin >> n >> m >> k;
// 检查n和m的奇偶性
if (n % 2 != m % 2) {
cout << 0 << '\n';
return 0;
}
// 初始化行和列约束,初始值为1(要求奇数个1)
vector<int> r(n, 1);
vector<int> c(m, 1);
// 记录每行和每列剩余未填的网格数
vector<int> row_rest(n, m);
vector<int> col_rest(m, n);
// 存储固定值
vector<tuple<int, int, int>> fixes;
for (int i = 0; i < k; i++) {
int x, y, z;
cin >> x >> y >> z;
x--; y--; // 转换为0-indexed
fixes.push_back(make_tuple(x, y, z));
// 更新行和列约束(模2运算)
r[x] = (r[x] - z + 2) % 2;
c[y] = (c[y] - z + 2) % 2;
// 更新剩余未填网格数
row_rest[x]--;
col_rest[y]--;
}
int isolated_row = 0, isolated_col = 0;
// 检查孤立行:如果某行所有网格已填,则检查其约束是否为0
for (int i = 0; i < n; i++) {
if (row_rest[i] == 0) {
if (r[i] != 0) {
cout << 0 << '\n';
return 0;
}
isolated_row++;
}
}
// 检查孤立列:如果某列所有网格已填,则检查其约束是否为0
for (int j = 0; j < m; j++) {
if (col_rest[j] == 0) {
if (c[j] != 0) {
cout << 0 << '\n';
return 0;
}
isolated_col++;
}
}
// 复制约束数组用于非孤立部分调整
vector<int> new_r = r;
vector<int> new_c = c;
// 调整非孤立部分的约束
for (const auto& fix : fixes) {
int x = get<0>(fix);
int y = get<1>(fix);
int z = get<2>(fix);
// 行孤立且列非孤立:将固定值加到列约束
if (row_rest[x] == 0 && col_rest[y] != 0) {
new_c[y] = (new_c[y] + z) % 2;
}
// 行非孤立且列孤立:将固定值加到行约束
else if (row_rest[x] != 0 && col_rest[y] == 0) {
new_r[x] = (new_r[x] + z) % 2;
}
}
// 计算非孤立行和列的约束和
int sum_r = 0, sum_c = 0;
for (int i = 0; i < n; i++) {
if (row_rest[i] > 0) {
sum_r = (sum_r + new_r[i]) % 2;
}
}
for (int j = 0; j < m; j++) {
if (col_rest[j] > 0) {
sum_c = (sum_c + new_c[j]) % 2;
}
}
// 约束和必须相等(模2)
if (sum_r != sum_c) {
cout << 0 << '\n';
return 0;
}
// 计算连通块数量:非孤立部分(如果存在)为1个,加上所有孤立行和孤立列
int cc = 0;
if ((n - isolated_row) > 0 || (m - isolated_col) > 0) {
cc = 1;
}
cc += isolated_row + isolated_col;
// 计算自由变量数量
long long free_edges = (long long)n * m - k - (n + m - cc);
if (free_edges < 0) {
cout << 0 << '\n';
return 0;
}
// 计算2^free_edges mod 998244353
cout << mod_pow(2, free_edges, MOD) << '\n';
return 0;
}