HDU5671-Matrix 区间加减

来源:互联网 发布:a类网络ip地址 编辑:程序博客网 时间:2024/06/03 13:44
Problem Description
There is a matrix M that has n rows and m columns (1n1000,1m1000).Then we perform q(1q100,000) operations:

1 x y: Swap row x and row y
(1x,yn);

2 x y: Swap column x and column y
(1x,ym);

3 x y: Add y to all elements in row x
(1xn,1y10,000);

4 x y: Add y to all elements in column x
(1xm,1y10,000);
 

Input
There are multiple test cases. The first line of input contains an integerT(1T20) indicating the number of test cases. For each test case:

The first line contains three integers
n,m and q.
The following
n lines describe the matrix M.(1Mi,j10,000) for all (1in,1jm).
The following
q lines contains three integers a(1a4),x and y.
 

Output
For each test case, output the matrix M after all q operations.
 

Sample Input
23 4 21 2 3 42 3 4 53 4 5 61 1 23 1 102 2 21 1010 11 1 22 1 2
 

Sample Output
12 13 14 151 2 3 43 4 5 61 1010 1
Hint

Recommand to use scanf and printf


这是一题bestcoder的B题,题目本身是挺简单的,只要观察到一个性质:
当我们进行 行交换的时候,每个元素所对应的列是不变的;
当我们进行 列交换的时候,每个元素所对应的行是不变的。
那么,我们先考虑这个问题的简化版本:
一开始矩阵所有数值都为0,对行列进行题目中的操作,
就可以开两个数组,分别记录每一行  每一列的变化量。如果是交换的话,直接swap就可以。(具体的自己试一下就知道了)

但是题目中有个问题,就是矩阵每个元素是有初始值的。那么怎么办呢?
从我们已经解决的问题出发,思考  如何转化成我们已经解决的问题
我的方法是开了rowindex数组,记录目前第I行是原来(一开始)的第几行。
列同理,开了colindex数组。
最后把原来的数值加上去就可以了。
注意每行最后不能有空格,不然会PE
代码:
#include<bits/stdc++.h>using namespace std;const int maxn=1010;int m,n,q;int row[maxn],col[maxn],rowindex[maxn],colindex[maxn];int backup[maxn][maxn],num[maxn][maxn];void init(void){    memset(row,0,sizeof(row));    memset(col,0,sizeof(col));    for(int i=1;i<=n;i++)        rowindex[i]=i;    for(int i=1;i<=m;i++)        colindex[i]=i;    for(int i=1;i<=n;i++)        for(int j=1;j<=m;j++)            scanf("%d",&backup[i][j]);}int main(void){    int T,a,x,y;    cin>>T;    while(T--)    {        cin>>n>>m>>q;        init();        while(q--)        {            scanf("%d%d%d",&a,&x,&y);            if(a==1)            {                swap(row[x],row[y]);                swap(rowindex[x],rowindex[y]);            }            if(a==2)            {                swap(col[x],col[y]);                swap(colindex[x],colindex[y]);            }            if(a==3)                row[x]+=y;            if(a==4)                col[x]+=y;        }        for(int i=1;i<=n;i++)        {            for(int j=1;j<=m;j++)            {                num[i][j]=backup[rowindex[i]][colindex[j]]+row[i]+col[j];                if(j!=1)                    printf(" %d",num[i][j]);                else                    printf("%d",num[i][j]);            }            printf("\n");        }    }    return 0;}