Sicily 1036——令人纠结的数组下标

题意:给出一个密钥字符串,假设其长度为k,然后再给出一个明文字符串,以k为段长不断截出来,构成一个矩阵,最后一行剩余的空位随便怎么补齐,这样横着放好之后,再竖着一列一列输出,但是不是简单地从左到右,而是按照密钥字符串中的字符排序进行。要求输入密钥字符串和密文字符串,输出明文字符串。

 

数组的下标计算颇为纠结,像这种题就应该老老实实在草稿纸上模拟一下,空想很容易想错的。代码如下:

 

 1 // Problem#: 1036
 2 // Submission#: 2194504
 3 // The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
 4 // URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
 5 // All Copyright reserved by Informatic Lab of Sun Yat-sen University
 6 #include<iostream>
 7 #include<cstring>
 8 #include<cstdio>
 9 
10 using namespace std;
11 
12 int main()
13 {
14     char keyword[11];
15     char ciphertext[101];
16     char mat[101][101];
17     int order[11];
18 
19     while((cin>>keyword) && strcmp(keyword, "THEEND") != 0)
20     {
21         cin>>ciphertext;
22         int length = strlen(keyword);
23         int size = strlen(ciphertext)/length;
24         for(int i = 0; i < length; i ++)
25             order[i] = i;
26         for(int i = length - 2; i > -1; i --)
27             for(int j = i; j < length - 1; j ++)
28                 if(keyword[j] > keyword[j+1])
29                 {
30                     char temp1 = keyword[j];
31                     keyword[j] = keyword[j+1];
32                     keyword[j+1] = temp1;
33                     int temp2 = order[j];
34                     order[j] = order[j+1];
35                     order[j+1] = temp2;
36                 }
37         
38         for(int i = 0; i < size; i ++) 
39             for(int j = 0; j < length; j ++)
40                 mat[i][order[j]] = ciphertext[j * size + i];
41         //每一行后面已经没有'\0'了,所以不要偷懒,二重循环输出每个字符,不然会很烫烫烫烫烫烫烫烫烫烫烫的
42         for(int i = 0; i < size; i ++)
43             for(int j = 0; j < length; j ++)
44                 cout<<mat[i][j];
45         cout<<endl;
46     }
47     return 0;
48 }                                     

 

posted @ 2013-08-29 00:30  WarBean  阅读(387)  评论(0编辑  收藏  举报