Kris works in a large company "Blake Technologies". As a best engineer of the company he was assigned a task to develop a printer that will be able to print horizontal and vertical strips. First prototype is already built and Kris wants to tests it. He wants you to implement the program that checks the result of the printing.
Printer works with a rectangular sheet of paper of size n × m. Consider the list as a table consisting of n rows and m columns. Rows are numbered from top to bottom with integers from 1 to n, while columns are numbered from left to right with integers from 1 to m. Initially, all cells are painted in color 0.
Your program has to support two operations:
- Paint all cells in row ri in color ai;
- Paint all cells in column ci in color ai.
If during some operation i there is a cell that have already been painted, the color of this cell also changes to ai.
Your program has to print the resulting table after k operation.
The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 5000, n·m ≤ 100 000, 1 ≤ k ≤ 100 000) — the dimensions of the sheet and the number of operations, respectively.
Each of the next k lines contains the description of exactly one query:
- 1 ri ai (1 ≤ ri ≤ n, 1 ≤ ai ≤ 109), means that row ri is painted in color ai;
- 2 ci ai (1 ≤ ci ≤ m, 1 ≤ ai ≤ 109), means that column ci is painted in color ai.
Print n lines containing m integers each — the resulting table after all operations are applied.
3 3 3 1 1 3 2 2 1 1 2 2
3 1 3 2 2 2 0 1 0
5 3 5 1 1 1 1 3 1 1 5 1 2 1 1 2 3 1
1 1 1 1 0 1 1 1 1 1 0 1 1 1 1
The figure below shows all three operations for the first sample step by step. The cells that were painted on the corresponding step are marked gray.
题意:给你一个n*m的矩阵,初始值为0,输出进行k次操作后的矩阵。
直接暴力处理的话,复杂度可以达到Maxn*Maxk或者Maxm*Maxk,为1e10,TLE是肯定的。以下为TLE的代码,可以试试。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<cmath>
using namespace std;
const int maxn = 5005;
int Map[maxn][maxn],n,m,k,a,b,c;
int main()
{
scanf("%d%d%d",&n,&m,&k);
for(int i=0;i<k;i++){
scanf("%d%d%d",&a,&b,&c);
if(a==1){
for(int j=1;j<=m;j++){
Map[b][j]=c;
}
}
else{
for(int j=1;j<=n;j++){
Map[j][b]=c;
}
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
printf("%d ",Map[i][j]);
}
printf("\n");
}
return 0;
}
#include <cstdio>
#include <algorithm>
const int N = 5000, K = (int)1e5 + 1;
int n, m, k;
int t, p;
int l[N], c[N], x[K];
int main() {
scanf("%d%d%d", &n, &m, &k);
x[0] = 0;
for (int i = 1; i <= k; ++i) {
scanf("%d%d%d", &t, &p, &x[i]);
if (t == 1)
l[--p] = i;
else
c[--p] = i;
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j)
printf("%d ", x[std::max(l[i], c[j])]);
putchar('\n');
}
return 0;
}
它运用到了类似指针一样的思想,把每块东西都独立出来处理,灵活性和高效性十分突出。从代码可以看出,x[i]表示存储各行列要赋予的值;l [p]或c [p]表示i的值;由于p被输入的次序控制着,后输入的p会把前面输入的p值覆盖,达到节省每次修改行列值繁琐操作的时间。在输出的时候,只要得到当前位置较后输入的那个值的i,即可找到对应的值x [i]。