POJ 2039 To and Fro(我的水题之路——解密,N个字符的正逆序)

来源:互联网 发布:win7系统制作mac os x 编辑:程序博客网 时间:2024/05/04 13:01
To and Fro
Time Limit: 1000MS Memory Limit: 30000KTotal Submissions: 7357 Accepted: 4853

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 yh p k n ne l e a ir a h s ge c o n hs e m o tn 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.

Sample Input

5toioynnkpheleaigshareconhtomesnlewx3ttyohhieneesiaabss0

Sample Output

theresnoplacelikehomeonasnowynightxthisistheeasyoneab

Source

East Central North America 2004

题目中要求你对于给出的密文还原成原文。
如:原文为theresonoplacelikehomeonasnowynightx,先将这个字符串分成N列书写。如果没有写满就用x填充,写成如下队列:
t o i o yh p k n ne l e a ir a h s ge c o n hs e m o tn l e w x
对于奇数行,从左向后书写,对于偶数行,从右向左书写,得到密文:
toioynnkpheleaigshareconhtomesnlewx

用模拟还原解题,将密文字符串存储到数组中,将所有的字符按照加密方法还原回去。(数组下标从0开始)
一共进行N次读入,对于第i次读取,用j定位行数
如果j为偶数,输出N*j+i;
如果j为奇数,输出N*(j+1)-1-i.

注意点:
1)对于规律题,先用笔计算出输出规律再敲代码,不要凭感觉直接写代码,这样可以节省时间,而且思路更清晰。

代码(1AC):
#include <cstdio>#include <cstdlib>#include <cstring>char str[210];int N;int main(void){    int i, j;    int len, M;    while (scanf("%d", &N), N != 0){        getchar();        gets(str);        len = strlen(str);        M = (int)((double)N / (double)len + 0.999999);        for (i = 0; i < N; i++){            for (j = 0; j * N < len; j++){                if (j % 2 == 0){                    printf("%c", str[N * j + i]);                }                else if (j % 2 == 1){                    printf("%c", str[N * (j + 1) - 1 - i]);                }            }        }        printf("\n");    }    return 0;}




原创粉丝点击