题目;
Description:
You are given a matrix M of type 1234x5678. It is initially filled with integers 1...1234x5678 in row major
order. Your task is to process a list of commands manipulating M. There are 4 types of commands:
"R x y" swap the xth and yth row of M; 1<=x, y<=1234.
"C x y" swap the xth and yth column of M; 1<=x, y<=5678.
"Q x y" write out M(x, y); 1<=x<=1234.1<=y<=5678.
"W z" write out x and y where z=M(x, y). 1<=z<=7006652 (1234 * 5678)
Input
The input file contains several test cases. The first line is N: the number of test cases. Then follows N lines.
A list of valid commands.1 <= N <= 10000.
Output
For each "Q x y" write out one line with the current value of M(x, y), for each "W z" write out one line with
the value of x and y (described as above) separated by a space.
Sample Input Sample Output:
输入:
10
R 1 2
Q 1 1
Q 2 1
W 1
W 5679
C 1 2
Q 1 1
Q 2 1
W 1
W 5679
对应输出:
5679
1
2 1
1 1
5680
2
2 2
1 2
题目大意:
本题意思为有一个1234*5678的矩阵,每个点对应的数为这个点在矩阵中的位置,例如:第一行第一列为1;第一行最后一列为5678。对这个矩阵主要有四种操作;分别为换行(R),换列(C),输出对应坐标的数(Q);根据数输出赌赢的行和列(W);"R,x,y"是把第x行和第y行相互交换,"C,X,y"是把第x列和第y列相互交换,"Q,x,y"是输入第x行第y列的数,"W,x"数输入x所在的行和列。
解题思路:
由于所给的矩阵过大,所以设置二维数组进行遍历操作肯定会超时,所以可以设置两个一维数组r[1240],c[5680],数组设置大一些是为了防止访问越界,分别对这两个一维数组赋值为r[1240]={0,1,2....1239},c[5680]={0,1,2,3...5679},对数组操作从第二位开始,这样比较方便计算;这样在进行换行或者换列操作时只需要改变r[i],c[i]所存储的数即可。因为每一个数都可以有(r[i]-1)*5678+c[j]表示,这样就不需要二维数组,而且可以节约大部分的时间。简化程序,减小内存使用量。具体实现由以下程序来看。
运行程序:
#include<iostream>
using namespace std;
int main()
{
int r[1240]={0};
int c[5680]={0};
int i,j,m,n;
char str;
for(i=1;i<1240;i++) 对数组初始化
r[i]=i;
for(i=1;i<5680;i++)
c[i]=i;
int N;
cin>>N;
while(N--)
{
cin>>str;
if(str=='R') 换行操作
{
int mem;
cin>>m;
cin>>n;
mem=r[m];
r[m]=r[n];
r[n]=mem;
}
else if(str=='C') 换列操作
{
int num1;
cin>>m;
cin>>n;
num1=c[m];
c[m]=c[n];
c[n]=num1;
}
else if(str=='Q') 计算数的大小
{
cin>>m;
cin>>n;
int num2=(r[m]-1)*5678+c[n];
cout<<num2<<endl;
}
else if(str=='W') 计算数的位置
{
int num3;
cin>>num3;
m=num3%5678;
n=(num3/5678)+1;
if(m==0) 假如m=0;则可以认为是上一行的最后一个数。
{
m=5678;
n--;
}
for(j=1;j<=1234;j++) 遍历操作,找到数所在的行列数
{
if(r[j]==n)
{
cout<<j<<" ";
break;
}
}
for(j=1;j<=5678;j++)
{
if(c[j]==m)
{
cout<<j<<endl;
break;
}
}
}
}
return 0;
}
解题感想:
本题涉及的数据较大,如果开二维数组来存储,浪费太多的时间,而且在初始化时两个for循环就足以让程序超时,所以只能运用两个一维数组,在以后遇到二维数组的问题,如果数据较大,则寻找其中的规律,尽量转换为一维数组来进行操作。操作时之重要的是注意数组的越界,所开的数组一定要尽量开的大一些,这样不至于数组越界,还有就是要理清程序中各个变量名所代表的的意思,尽量不要弄混。取变量名是尽量贴近所代表的的意思。