Monday, February 21, 2011


Problem Links:



SPOJ Problem Set (classical)

400. To and Fro

Problem code: TOANDFRO

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
Your job is to recover for Larry the original message (along with any extra padding letters) from the encrypted one.


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.


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







Hint: The length of the string is always the multiplication of the number of input number.

Source Code:

 1 //Mon Feb 21 20:13:38 CST 2011
 2 #include <vector>
 3 #include <list>
 4 #include <map>
 5 #include <set>
 6 #include <deque>
 7 #include <queue>
 8 #include <stack>
 9 #include <bitset>
10 #include <algorithm>
11 #include <functional>
12 #include <numeric>
13 #include <utility>
14 #include <sstream>
15 #include <iostream>
16 #include <iomanip>
17 #include <cstdio>
18 #include <cmath>
19 #include <cstdlib>
20 #include <cctype>
21 #include <string>
22 #include <cstring>
23 #include <cstdio>
24 #include <cmath>
25 #include <cstdlib>
26 #include <ctime>
28 using namespace std;
30 int main(int argc, char* argv[]) {
31     //freopen("", "r", stdin);
32     //freopen("output.out", "w", stdout);
33     int t;
34     while (cin >> t && t) {
35         string s1;
36         cin >> s1;
37         string s2(s1);
38         int rows = s1.size() / t;
39         for (int i = 0; i < (int) s1.size(); i++) {
40             int m = i / t;
41             //check which line it's at, odd line or even line.
42            int n = (m % 2 == 0 ? i % t : t - 1 - i % t);
43            s2[n * rows + m] = s1[i];
44         }
45         cout << s2 << endl;
46     }
47     //fclose(stdin);
48     //fclose(stdout);
49     return 0;
50 }

No comments :