fork(5) download
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4. #include <map>
  5. #include <cmath>
  6. using namespace std;
  7. string a = "send";
  8. string b = "more";
  9. string c = "money";
  10.  
  11. bool satisfyCondition(map <char, int> assigned){
  12. if(assigned[a[0]] == 0 || assigned[b[0]] == 0 || assigned[c[0]] == 0) return 0;
  13. int stringA = 0;
  14. int stringB = 0;
  15. int stringC = 0;
  16.  
  17. for(int i = 0; i< a.length(); i++){
  18. stringA = stringA*10 + assigned[a[i]];
  19. }
  20. for(int i = 0; i< b.length(); i++){
  21. stringB = stringB*10 + assigned[b[i]];
  22. }
  23. for(int i = 0; i< c.length(); i++){
  24. stringC = stringC*10 + assigned[c[i]];
  25. }
  26. if((stringA + stringB) == stringC) return 1;
  27. else return 0;
  28. }
  29.  
  30. bool CalculatePuzzle(map<char, int> &assigned, string lettersToAssign,string fullString){
  31.  
  32. if(lettersToAssign.empty()){
  33. // for(int i = 0 ; i< fullString.size();i++ )
  34. // cout << fullString[i] << " " << assigned[fullString[i]] << endl;
  35. // cout << endl << endl;
  36. return satisfyCondition(assigned);
  37. }
  38.  
  39. for(int i = 9; i >=0; i--){
  40. char toAssign = lettersToAssign[0];
  41. // cout << toAssign << endl;
  42. bool present = 0;
  43. for(map <char, int>::iterator it = assigned.begin(); it != assigned.end(); it++)
  44. {
  45. if(it->second == i){
  46. present = 1;
  47. }
  48. }
  49. if(present == 1) continue;
  50. assigned[toAssign] = i;
  51. bool b = CalculatePuzzle(assigned, lettersToAssign.substr(1),fullString);
  52. if(b == 1)
  53. return 1;
  54. else{
  55. assigned[toAssign] = -1;
  56. }
  57. }
  58. return 0;
  59. }
  60.  
  61. int main(){
  62. map <char, int> assigned;
  63. string letters;
  64. int frequency[26] = {0};
  65. for(int i = 0; i< a.length(); i++){
  66. if(frequency[a[i]-'a']++ == 0){
  67. //assigned[a[i]]++;
  68. letters+= a[i];
  69. }
  70. }
  71. for(int i = 0; i< b.length(); i++){
  72. if(frequency[b[i]-'a']++ == 0){
  73. //assigned[b[i]]++;
  74. letters+= b[i];
  75. }
  76. }
  77. for(int i = 0; i< c.length(); i++){
  78. if(frequency[c[i]-'a']++ == 0){
  79. //assigned[c[i]]++;
  80. letters+= c[i];
  81. }
  82. }
  83. for(int i = 0; i < letters.size(); i++){
  84. assigned[letters[i]] = -1;
  85. }
  86. // cout << letters << endl;
  87. bool b = CalculatePuzzle(assigned,letters,letters);
  88. if (b == 0) {
  89. cout << "No solution" << endl;
  90. }
  91. else{
  92. for(map <char, int>::iterator it = assigned.begin(); it != assigned.end(); it++){
  93. cout << it->first << " " << it->second << endl;
  94. }
  95. }
  96. cout << endl;
  97.  
  98. }
  99.  
Success #stdin #stdout 0.08s 3480KB
stdin
Standard input is empty
stdout
d 7
e 5
m 1
n 6
o 0
r 8
s 9
y 2