1129: An Old
时间限制: 1 Sec 内存限制: 128 MB
提交: 492 解决: 88
[提交][状态][讨论版]
题目描述
给定一个n*m的矩阵,要求支持下面的操作:
0 x y:交换第x行与第y行
1 x y:交换第x列与第y列
输入
多组数据。对于每组测试数据,第一行包含三个数n,m,k(1<=n,m<=1000;1<=k<=100000),分别表示行数,列数,操作数。
接下来n行,每行m个整数,表示初始的矩阵,矩阵中每个数小于10^9。
接下来k行每行一个操作,格式如题目所述。
输出
对于每组数据,输出完成所有操作后的矩阵。
样例输入
3 2 2
1 2
3 4
5 6
0 1 3
1 1 2
样例输出
6 5
4 3
2 1
提示
输出请不要有多余的空格!!
来源
lbz007
这个题由于其数据范围巨大,如果就是循规蹈矩地去交换行或者列的话,其交换可能要达到1000100000这么大,再加上多组数据的条件所以最后一定超时。所以就要想办法优化这个过程。
注意到这些操作的顺序其实是没有关系的。那么可以先对所有的列进行处理,而只对列进行处理的时候。开始处理和处理完毕后,某一行其实只是被赋值到某一个特定的行上去了,那么我只需要把他最后直接赋值到那一行就行了,所以我只需要存储下他最后去了哪行就好了。这样就可以节约大量交换的时间。最后只需要进行2n*m次的赋值就可以了
//http://acm.xidian.edu.cn/problem.php?id=1129
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std;
const int MOD = int(1e9) + 7;
//int MOD = 99990001;
const int INF = 0x3f3f3f3f;
//const LL INFF = 0x3f3f3f3f3f3f3f3fLL;
//const DB EPS = 1e-9;
//const DB OO = 1e20;
//const DB PI = acos(-1.0); //M_PI;
const int fx[] = {-1, 1, 0, 0};
const int fy[] = {0, 0, -1, 1};
const int maxn=1000 + 5;
typedef struct node{
int x,y;
}node;
node r[100001],c[100001];
int n,m,k;
int juzhen[maxn][maxn],res[maxn][maxn];
void rf(int lenr){
int a[maxn];
for(int i=1;i<=n;i++) a[i]=i;
for(int i=0;i<lenr;i++){
int t=a[r[i].x];
a[r[i].x]=a[r[i].y];
a[r[i].y]=t;
}
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
res[i][j]=juzhen[a[i]][j];
}
void cf(int lenc){
int a[maxn];
for(int i=1;i<=m;i++) a[i]=i;
for(int i=0;i<lenc;i++){
int t=a[c[i].x];
a[c[i].x]=a[c[i].y];
a[c[i].y]=t;
}
for(int i=1;i<=m;i++)
for(int j=1;j<=n;j++)
juzhen[j][i]=res[j][a[i]];
}
int main(){
while(scanf("%d%d%d",&n,&m,&k)==3){
int lenr=0,lenc=0;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
scanf("%d",&juzhen[i][j]);
while(k--){
int kase;
scanf("%d",&kase);
if(kase) {scanf("%d%d",&c[lenc].x,&c[lenc].y);lenc++;}
else {scanf("%d%d",&r[lenr].x,&r[lenr].y);lenr++;}
}
rf(lenr);
cf(lenc);
for(int i=1;i<=n;i++){
for(int j=1;j<m;j++){
printf("%d ",juzhen[i][j]);
}
printf("%d\n",juzhen[i][m]);
}
}
return 0;
}