UVa 11697 - Playfair Cipher Solution

#include <iostream>
#include <vector>
#include <string>
// #include <sstream>
#include <map>
#include <utility>
using namespace std;
int main(){
    int t;
    cin>>t;
    while(t--){
        string key,txt;
        ws(cin);
        getline(cin,key);
        vector<int> alph(26);
        vector<vector<char> > table(5,vector<char>(5));
        int i=0,j=0;
        for(int k=0;k<key.size();k++){
            if(key[k]!=' '){
                if(!alph[key[k]-97]){
                    alph[key[k]-97]=1;
                    table[i][j]=key[k];
                    j++;
                    if(j==5)
                        i++,j=0;
                }
            }
        }
        for(int k=0;k<26;k++){
            if(!alph[k]&&97+k!=int('q')){
                alph[k]=1;
                table[i][j]=char(97+k);
                j++;
                if(j==5)
                    i++,j=0;
            }           
        }
        // for(auto a:table){
        //     for(auto b:a)
        //         cout<<b<<' ';
        //     cout<<endl;
        // }
        map<char,pair<int,int> > mp;
        for(int i=0;i<5;i++){
            for(int j=0;j<5;j++){
                mp[table[i][j]]={i,j};
            }
        }
        getline(cin,txt);
        string ttxt;
        for(int i=0;i<txt.size();i++){
            if(txt[i]==' ')
                continue;
            else
                ttxt.push_back(txt[i]);
        }
        txt=ttxt;
        string ans;
        for(int i=0;i<txt.size();i++){
            string tmp;
            if(i==txt.size()-1||txt[i]==txt[i+1]){
                tmp=string(1,txt[i])+"x";
            }
            else{
                tmp=txt.substr(i,2);
                i++;
            }
            // cout<<tmp<<endl;
            if(mp[tmp[0]].first==mp[tmp[1]].first){
                tmp[0]=table[mp[tmp[0]].first][(mp[tmp[0]].second+1)%5];
                tmp[1]=table[mp[tmp[1]].first][(mp[tmp[1]].second+1)%5];
            }
            else if(mp[tmp[0]].second==mp[tmp[1]].second){
                tmp[0]=table[(mp[tmp[0]].first+1)%5][mp[tmp[0]].second];
                tmp[1]=table[(mp[tmp[1]].first+1)%5][mp[tmp[1]].second];
            }
            else{
                int t1=mp[tmp[0]].second,t2=mp[tmp[1]].second;
                t1^=t2;
                t2^=t1;
                t1^=t2;
                tmp[0]=table[mp[tmp[0]].first][t1];
                tmp[1]=table[mp[tmp[1]].first][t2];
            }
            tmp[0]=tmp[0]-97+65;
            tmp[1]=tmp[1]-97+65;
            ans+=tmp;
        }
        cout<<ans<<endl;
    }
}

Comments