sicily 1007. To and Fro

Description
Mo and Larry have devised a way of encrypting messages. They first decide secretly on the number of columns and write the message (letters only) down the columns, padding with extra random letters so as to make a rectangular array of letters. For example, if the message is "There's no place like home on a snowy night" and there are five columns, Mo would write down t o i o y h p k n n e l e a i r a h s g e c o n h s e m o t n l e w x Note that Mo includes only letters and writes them all in lower case. In this example, Mo used the character `x' to pad the message out to make a rectangle, although he could have used any letter. Mo then sends the message to Larry by writing the letters in each row, alternating left-to-right and right-to-left. So, the above would be encrypted as toioynnkpheleaigshareconhtomesnlewx Your job is to recover for Larry the original message (along with any extra padding letters) from the encrypted one.

Input
There will be multiple input sets. Input for each set will consist of two lines. The first line will contain an integer in the range 2 . ..20 indicating the number of columns used. The next line is a string of up to 200 lower case letters. The last input set is followed by a line containing a single 0, indicating end of input.

Output
Each input set should generate one line of output, giving the original plaintext message, with no spaces.

题解:拿到一个数字n和一串字符,如

5
toioynnkpheleaigshareconhtomesnlewx

将字符化成n个一行,即n列
toioy
nnkph
eleai
gshar
econh
tomes
nlewx

偶数行倒转
toioy
hpknn /* 倒转 */
eleai
rahsg /* 倒转 */
econh
semot /* 倒转 */
nlewx

竖着打印出来
theresnoplacelikehomeonasnowynightx

解题思路:先将偶数行倒转

再输出,i从0到strlen(str),输出所有i%n = 0的字符,再输出所有i%n = 1的字符....到所有i%n = n-1的字符,即隔n个字符输出,直到全部字符都输出完

AC代码

View Code
 1 #include<stdio.h>
 2 #include<string.h>
 3 void reverse( char *start, int n );
 4 int main()
 5 {
 6     char str[210] = {0};
 7     int i, j, n;
 8     int len;
 9     
10     while ( scanf("%d", &n) && n != 0 )
11     {
12         getchar();
13         
14         gets(str);
15         len = strlen(str);
16         
17         for( i = n; i < len; i = i + 2 * n )
18                 reverse( str + i, n );
19         
20         for( i = 0; i < n; i++ )
21             for( j = 0; j < len; j++ )
22                 if( j % n == i )
23                     printf("%c", str[j]);
24                     
25         printf("\n");
26     }
27     
28     return 0;
29 }
30 
31 void reverse( char *start, int n )
32 {
33     int i;
34     char temp;
35     
36     for ( i = 0; i < n / 2; i++ )
37     {
38         temp = *(start + i);
39         *(start + i) = *(start + n - i - 1);
40         *(start + n - i - 1) = temp;
41     }
42     
43     return;
44 }
原文地址:https://www.cnblogs.com/joyeecheung/p/2820793.html