POJ1449 & ZOJ1036 Enigma (Simple enumeration)

Source: Internet
Author: User
Tags reflector

This article is purely original, reproduced please indicate the source. Thank you.

Topic Portal: http://poj.org/problem?id=1449

Time Limit: 1000MS Memory Limit: 10000K

Description

During the Second World War, the German military forces mainly used one special machine to secure their communication:the Enigma (see Figure 4). Breaking the Enigma cipher is one of the main success stories of Allied cryptanalysis and the triumph were mainly attribute D to the emergence of digital computation and the genius of the people working at Bletchley Park, the secret cryptanalysis Headquarters in England. The reason for this was, while Enigma are certainly secure against pen and paper attacks, it is quite easily breakable Using digital computers.


Figure 4:an Enigma Machine (picture source:http://www.nsa.gov/museum/enigma.html).
The ENIGMA is a rotor machine, a cipher method which is popular at that time. A rotor is an insulated disk on which electrical contacts, one for each letter of the alphabet, being placed uniformly aroun D the periphery and on each side. An internal conduction path through the insulating material connects contacts in pairs, one on each side of the disk. An electric-entering on one side travels on a internal path through the rotor cross-section, emerging at one of T He contacts the other side (see Figure 5 for a 3D visualisation of the rotors). Figure 6 shows a schematic side view of the complete rotor system. It shows that the Enigma have three rotorsπ0,π2 plus an additional reflecting rotorπr.

The input to Enigma is a stream of alphabetic characters without blanks. Every character is subject to the following steps:

1. The plaintext is subject to an initial permutation IP which are implemented by a plugboard.

2. The character resulting from step 1 is sent through the three rotorsπ0,π2.

3. The resulting character is then sent through the reflecting Rotorπr.

4. The character from step 3 are passed back through the rotorsπ2,π0 (i.e., in the opposite direction).

5. The character from step 4 are subject to the inverse IP-1 of the initial permutation IP.

The interesting point on the use of rotors was that after processing each character, every rotor might was rotated by a C Ertain angle (i.e., a certain amount of letters) before processing the next character. With the Enigma, rotorπ0 are rotated by one in anti-clockwise direction with every new character. Whenπ0 have finished one round (i.e., after processing characters), rotorπ1 moves by one character. Similarly, rotorπ2 is rotated by one character whenπ1 have finished one revolution, and the reflecting Rotorπr moves whe Nπ2 has finished its rotation. Obviously,πr is the slowest of the four rotors.

The process described above can be used both for encryption and decryption, provided that the Permutationπr implemented B Y the Reflecting rotor is an involution. That Meansπr =πr-1, or, Equivalently,ξ=πr (ζ) wheneverζ=πr (ξ). Assume that condition holds.

The secret key of the Enigma consists of (1) The rotorsπ0,π2, Andπr, (2) The plugboard permutation IP, and (3) the Init ial rotational displacements K0, K1, K2, KR ofπ0,π2, andπr (see below). The rotors were changed infrequently and were selected from a set of four possible rotors in the Wehrmacht model.

Problem

You is time-warped to Bletchley Park together with your laptop and should help to decipher some messages which has been Intercepted over the day. You are given the entire ciphertext, parts of the plaintext, and parts of the Enigma key. Your task is to determine the correct key and finally complete the plaintext by decoding the ciphertext.

Input

The first line contains the number of scenarios.

Each scenario begins with the secret key of the Enigma. The secret key is specified by 6 lines. The first four lines contain a specification of the rotorsπ0,π2 andπr as a sequence in lowercase alphabetic characters. Character I (1<=i<=26) gives the mapping of the i-th Character of the alphabet (e.g., "Bha ..." means that "a" is Ma pped to "B", "B" was mapped to "H", "C" was mapped to "a" etc.). Physically, the sequence of characters is given in clockwise direction looking from the front of the rotor stackπ0. . . , Πr. After the rotors follows a similar line giving the plugboard permutation IP. Finally, the sixth line of the key gives the initial displacement K0, K1, K2, KR of the four rotorsπ0,π2, Andπr as a St Ring of four characters where "a" means that the rotor are in it original position (as defined by the rotor specification above), "B" means that it's rotated by one position in the usual. For example, "Dgaa" means the rotorπ0 has initial displacement 3,π1 hAs 6, Andπ2,πr is both in their original position. 

After the key follow-lines, each containing at least 1 and at most of the lowercase letters, and no other characters. The first line contains the plaintext and the second line contains the ciphertext. The plaintext and any part of the key is incomplete, i.e, some positions in the strings could be question marks "?". The number of question marks in the input would be is at most 3.

Output

The output for each scenario begins with a line containing "scenario #i:", where I am the number of the scenario starting at 1. The next line is to output the completed, decrypted plaintext. You can assume this a solution exists and that it's unique. Terminate the output for each scenario with a blank line.

Sample Input

2wfbtiznuvcqejpokshxgmadyrlhmrgnqpkjcaivwluebfzsyxtdodruahlbfzvgmwckxpiqysontjeowtvskypjifmluahrqecndbzgx? Bcdefghijklmnopqrstuvwxyzaaaamanyorganizationsrelyoncom?? Tersgrsuztldsznkwnerdpfbovvqnobkyiqnoqzunvhtxwryfebicmjpklsgdazupogrskynxtwdfqvbliejcmhakzvlyjuodmscewxtfbphriqgnagbcnyla Ztwkfmdspqvoiurjxehrfyhkxbuvplgtqmdiewjoszncadmeo??? Ave

Sample Output

Scenario #1: Manyorganizationsrelyoncomputersscenario #2: ACM

This problem long I this kind of English bad Leng looked at half a day.

This is the 2001 XX-Europe live game, the title is smelly and long, the key is actually a full water problem, the key is the online temporary still can not find the problem, only Zhao Dragon Boat wrote "ACM International College Student Program design Contest 1" Inside there are mentioned this problem, but the explanation is not enough detailed, Did not explain the principle of the machine, so look at the day to understand more, and then decided to write an article to explain it well.



The main idea is this: (Let me explain the machine first)

First of all, Enigma as the German World War II encryption and decryption device, this problem completely restored the structure of this genius.

It consists of a replacement disk, 3 displacement rotors, and a reflector rotor disk.

The first is the replacement disk is a simple replacement of the cipher, the forward pass when a is replaced by X, the reverse through the x is replaced by a, it is fixed, but also the most basic of the simplest encryption method. The "Dancing villain" in the "Sherlock Holmes Collection" is used in this way, simply to replace the original 26 letters with 26 new symbols, although the replacement of the 26 symbols is also taken from 26 letters, but they do not represent the original meaning after replacement. Instead, replace the 26 characters with the original letters.


Then the hardest thing to understand is the 3 displacement rotors, which is the essence of the machine. Yesterday did not see the circuit diagram when I have been thinking how to achieve, and then saw the circuit diagram instantly understand. Put the picture below.


This is a working schematic diagram of a replacement rotor disk.

We can see that both the plaintext (the left disk) and the ciphertext (right disk) are arranged sequentially and unchanged, changing the middle rotor circuit circle. And we can see that the circuit of the replacement circuit is the same, then if a at the beginning of a connected to D, then the representative is connected to a point of this circuit is connected to 3, then once the rotor down one, not B connected to the D point, but B point to get the original at point a circuit, Then B will be connected to the place where it is 3 down, and vice versa. Then each disk in the initial state of the connection, it represents the disk 26 points of the circuit connection condition, that is, the key.

If the understanding of this principle, then the last reflection of the rotor disk is very good understanding, nothing is to remove the right disk of the rotor, and the left side of the point 22 connected together, constitute 13 pairs, of course, rotation will also bring a change in pairing.

And when will these four rotating discs turn? The rule is this: after each processing of a character, the 1th rotor counter-clockwise to a character, if the 1th rotor disk 26, that is, the processing of 26 characters, the second rotor counter-clockwise rotation of a character, and then the second turn 26 next to the third one character, fourth and so on. Of course, we can start by moving each disk a few characters, this toggle does not count the number of rotations.

The above is the principle of this machine explanation, but also the core of the problem, as long as the understanding of this point, the problem is water.


Test instructions: Now give you such a machine, first tell you the key of four disk (it for each key, is given by 26 characters per line, the first x line of the I character represents the letter ' a ' +i-1 in the initial state through the X-disk should be what), Then the fifth line tells you the corresponding relationship of the fixed simple substitution disk (the same way as above), the next line sixth gives you a line of four characters, the first character indicates the initial state, the I disk is c[i]-' a ' character. And then the seventh line gives you a clear text, and line eighth gives you the ciphertext after the text is encrypted in the state of the machine. And now I'm telling you, there are up to 3 characters in the eight-line string above that are not clearly visible, so when you read it, use '? ' Instead, then please find these three '? ' The correct character should correspond to the output of the complete plaintext (the title guarantees that each set of test data has and only one solution).

So what is the order of this cipher in the title:

1, each character first forward through the simple displacement plate

2. The characters obtained by step 1 are then positive through 1, 2, 3, three rotor replacement plates.

3. The characters obtained by Step 2 are then passed through the reflector rotor replacement plate.

4. The characters obtained by Step 3 are reversed by 3, 2, 1 and three rotor replacement plates.

5. The characters obtained by step 4 are reversed by the simple substitution plate to get clear text.

6, each character completes above five steps, each rotor rotates, prepares for the next character processing.


Idea: Get this problem first analysis, only 3 characters are not sure, and each after 26 cases, so there is only 26*26*26=17526 kind of possibility, completely can enumerate out and then detect whether it can meet the decryption process.

So happily with the DFS enumeration and then detected.

Paste the code below.

#include <cstdio> #include <cmath> #include <cstring> #include <string> #include <map># Include <vector> #include <iostream> #include <algorithm> #define MOO 1000000007//10^9+7#define PI ACOs ( -1.0) using namespace Std;char s[10][100];//the original 8-row string int a[10][100];//the 8-line string after the processing method is for each character-' a ' struct question    {int x; int y;}    que[5];//the position of the question mark at the location, the number of x line y character int cou;//The quantity of the question mark int cheek ()//detection function, for the current enumeration condition, if decryption is correct then return 1, otherwise return 0{int b1[100];    int b2[100];//The Vmcontext out, as it is modified so as to avoid any impact on the original data.    int Len=strlen (s[7]);    for (int i=0;i<len;i++) {b1[i]=a[4][a[7][i]];//The first pass of ciphertext through the operation of simple displacement plate b2[i]=a[6][i]; } int d[4][30];//each rotor forward through the circuit diagram int e[4][30];//the circuit diagram for (int. i=0;i<4;i++) {for (int j=0;j&l) When each rotor is passed backwards            t;26;j++) {int t=a[i][j]; d[i][j]=t-j;//forward through, from J to T, the circuit is + (T-J) e[i][t]=j-t;//reverse through, from T to J, the circuit is + (J-T)}} int c[4];//the current of each rotor replacement plate    Turning condition. for (int i=0;i<4;i++) c[i]=a[5][i];    for (int i=0;i<len;i++) {for (int j=0;j<=3;j++) {b1[i]+=d[j][(b1[i]+c[j]+26)%26];        b1[i]= (b1[i]+26)%26; }//the current character in turn forward through the 1, 2, 3 of these three plates, because the reflector working principle is no different from the ordinary, so also handy forward through for (int j=2;j>=0;j--) {b1[i]+=e[j][(B1[i]            +c[j]+26)%26];        b1[i]= (b1[i]+26)%26;        }//then reverse through the 3, 2, 1 of these three plates.                for (int j=0;j<26;j++)//Determine if this character is reversed by simply replacing the plate after it is not getting plaintext, if not, then the current enumeration error if (B1[I]==A[4][J]&AMP;&AMP;B2[I]!=J)        return 0;            The c[0]++;//rotates accordingly for each rotor, preparing for processing the next character if (c[0]==a[5][0]+26) {c[0]=a[5][0];            c[1]++;                if (c[1]==a[5][1]+26) {c[1]=a[5][1];                c[2]++;                    if (c[2]==a[5][2]+26) {c[2]=a[5][2];                    c[3]++;                if (c[3]==a[5][3]+26) c[3]=a[5][3]; }}}} return 1;} int dfs (int x) {if (X==cou) {       if (cheek () ==1) return 1;    return 0;        } for (int i=0;i<26;i++)//Enumerate every bit of ' a ' +i case {a[que[x+1].x][que[x+1].y]=i;    if (Dfs (x+1) ==1) return 1; } return 0;} void init () {//preprocessing eight line string, all points are processed into int type, convenient to operate, and put '? '        All extracted for (int i=0;i<8;i++) {int Len=strlen (s[i]);            for (int j=0;j<len;j++) {if (s[i][j]== '? ')                {cou++;                Que[cou].x=i;            Que[cou].y=j;        } else a[i][j]=s[i][j]-' a ';    }}}int Main () {int T;    cin>>t;    int dd=t;        while (t--) {for (int i=0;i<8;i++) scanf ("%s", S[i]);        cou=0;        Init ();        DFS (0);        printf ("Scenario #%d:\n", dd-t);        int Len=strlen (s[6]);        for (int i=0;i<len;i++) printf ("%c", a[6][i]+ ' a ');    printf ("\ n"); } return 0;}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

POJ1449 & ZOJ1036 Enigma (Simple enumeration)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.