fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int main(){
  4. int i,j,k,n;
  5. cout<<"Enter the message"<<endl;
  6. string s,origin;
  7. getline(cin,origin);
  8. cout<<"Enter the key"<<endl;
  9. string key;
  10. cin>>key;
  11. for(i=0;i<origin.size();i++)
  12. {
  13. if(origin[i]!=' ')
  14. s+= origin[i];
  15. }
  16. vector<vector<char> > a(5,vector<char>(5,' '));
  17. n=5;
  18. map<char,int> mp;
  19. k=0;
  20. int pi,pj;
  21. for(i=0;i<n;i++)
  22. {
  23. for(j=0;j<n;j++)
  24. {
  25. while(mp[key[k]]>0&&k<key.size())
  26. {
  27. k++;
  28. }
  29. if(k<key.size())
  30. {
  31. a[i][j]=key[k];
  32. mp[key[k]]++;
  33. pi=i;
  34. pj=j;
  35. }
  36. if(k==key.size())
  37. break;
  38. }
  39. if(k==key.size())
  40. break;
  41. }
  42. k=0;
  43. for(;i<n;i++)
  44. {
  45. for(;j<n;j++)
  46. {
  47. while(mp[char(k+'a')]>0&&k<26)
  48. {
  49. k++;
  50. }
  51. if(char(k+'a')=='j')
  52. {
  53. j--;
  54. k++;
  55. continue;
  56. }
  57. if(k<26)
  58. {
  59. a[i][j]=char(k+'a');
  60. mp[char(k+'a')]++;
  61. }
  62. }
  63. j=0;
  64. }
  65.  
  66. string ans;
  67. if(s.size()%2==1)
  68. s+="x";
  69. for(i=0;i<s.size()-1;i++)
  70. {
  71. if(s[i]==s[i+1])
  72. s[i+1]='x';
  73. }
  74.  
  75. map<char,pair<int,int> > mp2;
  76.  
  77. for(i=0;i<n;i++)
  78. {
  79. for(j=0;j<n;j++)
  80. {
  81. mp2[a[i][j]] = make_pair(i,j);
  82. }
  83. }
  84.  
  85. for(i=0;i<s.size()-1;i+=2)
  86. {
  87. int y1 = mp2[s[i]].first;
  88. int x1 = mp2[s[i]].second;
  89. int y2 = mp2[s[i+1]].first;
  90. int x2 = mp2[s[i+1]].second;
  91. if(y1==y2)
  92. {
  93. ans+=a[y1][(x1+1)%5];
  94. ans+=a[y1][(x2+1)%5];
  95. }
  96. else if(x1==x2)
  97. {
  98. ans+=a[(y1+1)%5][x1];
  99. ans+=a[(y2+1)%5][x2];
  100. }
  101. else
  102. {
  103. ans+=a[y1][x2];
  104. ans+=a[y2][x1];
  105. }
  106. }
  107. cout<<ans<<'\n';
  108. return 0;
  109. }
  110.  
  111.  
  112.  
  113.  
Success #stdin #stdout 0.01s 5312KB
stdin
rahul
5
stdout
Enter the message
Enter the key
qbexnv