Advertisement
Gustavo_Inzunza

Sum of digits

Aug 17th, 2013
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <cmath>
  4. #include <vector>
  5. #include <stdio.h>
  6. #include <string.h>
  7. using namespace std;
  8. int N,suma,cuadrado,limite,flag;
  9. std::vector<int> candidatos;
  10. bool Dp[901][8101];
  11. void Calcula(int profundidad,int sumas,int cuadrados)
  12. {
  13.     if(Dp[sumas][cuadrados])
  14.         return;
  15.     if (profundidad==limite or flag)
  16.     {
  17.         if (sumas==suma and cuadrados==cuadrado)
  18.             flag=1;
  19.         else if(sumas>suma or cuadrados>cuadrado)
  20.                 Dp[sumas][cuadrados]=1;
  21.         return;
  22.     }
  23.     for (int i = 1; i <= 9 and sumas+i<=suma and cuadrados+i*i<=cuadrado; ++i)
  24.     {
  25.         candidatos.push_back(i);
  26.         Calcula(profundidad+1,sumas+i,cuadrados+i*i);
  27.         if (flag)
  28.             return;
  29.         candidatos.pop_back();
  30.     }
  31.     Dp[sumas][cuadrados]=1;
  32. }
  33. int main()
  34. {
  35.     scanf("%d",&N);
  36.     for (int i = 0; i < N; ++i)
  37.     {
  38.         limite=suma/9,flag=0;
  39.         scanf("%d %d",&suma,&cuadrado);
  40.         if(suma<=cuadrado)
  41.         {
  42.             while(!flag and limite!=101)
  43.             {
  44.                 memset (Dp,0,sizeof(Dp));
  45.                 Calcula(0,0,0);
  46.                 limite++;
  47.             }
  48.             if(!flag)
  49.                 printf("No solution\n");
  50.             else
  51.             {
  52.                 for (int j = 0; j < candidatos.size(); ++j)
  53.                     printf("%d",candidatos[j]);
  54.                 printf("\n");
  55.             }
  56.         }
  57.         else
  58.             printf("No solution\n");
  59.         candidatos.clear();
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement