import java.util.*;

class 
 {
    public static String encrypt(String text, int key) {
        char[][] rail = new char[key][text.length()];

        for (int i = 0; i < key; i++)
            Arrays.fill(rail[i], '-');

        boolean down = false;
        int row = 0, col = 0;

        for (int i = 0; i < text.length(); i++) {
            if (row == 0 || row == key - 1)
                down = !down;
            rail[row][col++] = text.charAt(i);
            if (down)
                row++;
            else
                row--;
        }

        StringBuilder result = new StringBuilder();
        for (int i = 0; i < key; i++)
            for (int j = 0; j < text.length(); j++)
                if (rail[i][j] != '-')
                    result.append(rail[i][j]);

        return result.toString();
    }

    public static String decrypt(String cipher, int key) {
        char[][] rail = new char[key][cipher.length()];

        for (int i = 0; i < key; i++)
            Arrays.fill(rail[i], '-');

        boolean ddown = true;
        int row = 0, col = 0;

        for (int i = 0; i < cipher.length(); i++) {
            if (row == 0)
                ddown = true;
            if (row == key - 1)
                ddown = false;
            rail[row][col++] = '*';
            if (ddown)
                row++;
            else
                row--;
        }

        int index = 0;
        for (int i = 0; i < key; i++)
            for (int j = 0; j < cipher.length(); j++)
                if (rail[i][j] == '*' && index < cipher.length())
                    rail[i][j] = cipher.charAt(index++);

        StringBuilder result = new StringBuilder();
        row = 0;
        col = 0;

        for (int i = 0; i < cipher.length(); i++) {
            if (row == 0)
                ddown = true;
            if (row == key - 1)
                ddown = false;
            if (rail[row][col] != '*')
                result.append(rail[row][col++]);
            if (ddown)
                row++;
            else
                row--;
        }

        return result.toString();
    }

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("Enter the Plain text:");
        String plainText = s.nextLine();
        System.out.println("Enter the key:");
        int key = s.nextInt();
        String railFence = encrypt(plainText, key);
        System.out.println("Encrypted Message:" + railFence);
        String message = decrypt(railFence, key);
        System.out.println("Decrypted Message:" + message);
    }
}
