fork(8) download
  1. #include<bits/stdc++.h>
  2. using namespace std ;
  3.  
  4. int visit[10] , asgn[10] ;
  5. map<char , int> key;
  6. char text1[10] = "send" , text2[10] = "more" , ans[11] = "money" ;
  7.  
  8.  
  9. int solve_puzzle(char *letters , int index) {
  10.  
  11. if(index == 9) {
  12. int n1 = 0 , n2 = 0 , n3 = 0 ;
  13.  
  14. for(int i = 0 ; i < strlen(text1) ; i++)
  15. n1 = n1*10 + asgn[key.find(text1[i])->second] ;
  16.  
  17. for(int i = 0 ; i < strlen(text2) ; i++)
  18. n2 = n2*10 + asgn[key.find(text2[i])->second] ;
  19.  
  20.  
  21. for(int i = 0 ; i < strlen(ans) ; i++)
  22. n3 = n3*10 + asgn[key.find(ans[i])->second] ;
  23.  
  24. if(n1+n2 == n3) {
  25. cout << n1 << " + " << n2 << " = " << n3 << endl ;
  26. //return 1;
  27. }
  28. return 0 ;
  29. }
  30.  
  31. for(int i = 0 ; i < 10 ; i ++) {
  32. if(visit[i] == 0) {
  33. asgn[index] = i ;
  34. visit[i] = 1 ;
  35. //int flag =
  36. solve_puzzle(letters , index+1) ;
  37. // if(flag) return 1 ;
  38. visit[i] = 0 ;
  39. }
  40. }
  41. return 0 ;
  42. }
  43.  
  44. int main()
  45. {
  46. char letters[] = {'\0','s','e','n','d','m','o','r','y'};
  47. for(int i = 1 ; i < 10 ; i ++)
  48. key.insert( pair<char , int>(letters[i] , i ) );
  49.  
  50. if(!solve_puzzle(letters , 1))
  51. cout << "Not Possible";
  52. }
  53.  
  54. /*
  55.   SEND
  56. + MORE
  57. -------
  58.  MONEY
  59.  
  60.   9567
  61. + 1085
  62. -------
  63.  10652
  64.  
  65. NOTE : For single solution remove the comments...
  66.  
  67. */
  68.  
Success #stdin #stdout 0.3s 3464KB
stdin
Standard input is empty
stdout
2817 + 368 = 3185
2819 + 368 = 3187
3712 + 467 = 4179
3719 + 457 = 4176
3821 + 468 = 4289
3829 + 458 = 4287
5731 + 647 = 6378
5732 + 647 = 6379
5849 + 638 = 6487
6415 + 734 = 7149
6419 + 724 = 7143
6524 + 735 = 7259
6851 + 738 = 7589
6853 + 728 = 7581
7316 + 823 = 8139
7429 + 814 = 8243
7531 + 825 = 8356
7534 + 825 = 8359
7539 + 815 = 8354
7643 + 826 = 8469
7649 + 816 = 8465
8324 + 913 = 9237
8432 + 914 = 9346
8542 + 915 = 9457
9567 + 1085 = 10652
Not Possible