fork(4) download
  1. #include <iostream>
  2. #include <string>
  3. #include <cctype>
  4. using namespace std;
  5.  
  6. enum action { ENCRYPT, DECRYPT };
  7. string crypt(action type, int nrails, string data) {
  8. int cyclesize = 2*(nrails-1);
  9. string ret(data);
  10. int pos = 0, i, a;
  11. int& rpos = type ? i : pos, &dpos = type ? pos : i;
  12. for (int rail = 0; rail < nrails; ++rail) {
  13. for (i = rail, a = 2*rail; i < data.length(); a = cyclesize - a, i += a) {
  14. if (a==cyclesize) continue;
  15. ret[rpos] = data[dpos];
  16. ++pos;
  17. }
  18. }
  19. return ret;
  20. }
  21.  
  22. int main() {
  23. string data;
  24. action act;
  25. int nrails;
  26. cin >> data >> nrails;
  27. if (data == "enc") act = ENCRYPT;
  28. else if (data == "dec") act = DECRYPT;
  29. else {
  30. cout << "Unknown action.\n";
  31. return 1;
  32. }
  33.  
  34. while (isspace(cin.peek())) cin.ignore();
  35. getline(cin, data);
  36.  
  37. cout << crypt(act, nrails, data);
  38. return 0;
  39. }
Success #stdin #stdout 0s 3280KB
stdin
dec 6 AAPLGMESAPAMAITHTATLEAEDLOZBEN
stdout
ALPHABETAGAMMADELTAEPSILONZETA