Here you will find solutions of many problems on spoj. If you want solution of some problem which is not listed in blog or have doubt regarding any spoj problem (which i have solved) or any programming concept (data structure) you can mail me @ raj.nishant360@gmail.com
And my humble request to you all that don't copy the code only try to understand the logic and algorithm behind the code. I have started this because if you tried as hard as you can and still can't find any solution to the problem then you can refer to this.
You can read my answer how to start competitive programming CLICK HERE

Sunday, September 7, 2014

HPYNOSII-Happy Numbers II

Happy Numbers II

Given below code is for HPYNOSII spoj or Happy Numbers II spoj .

Initial array i have computed it from wikipedia where all happy numbers below 1000 are given.
#include <bits/stdc++.h>
using namespace std;
#define gc getchar_unlocked
int res[1001]={0,1,0,0,0,0,0,5,0,0,1,0,0,2,0,0,0,0,0,4,0,0,0,3,0,0,0,0,3,0,0,2,3,0,0,0,0,0,0,0,0,0,0,0,4,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,5,0,0,0,0,0,0,0,0,3,0,0,3,0,0,0,2,0,0,0,0,4,0,0,4,0,0,3,0,0,1,0,0,2,0,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,2,0,0,5,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,4,0,4,0,3,5,0,0,0,0,0,0,0,0,0,3,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,5,0,0,0,3,0,0,0,0,0,5,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,3,0,5,0,0,0,0,0,0,0,2,3,0,0,0,0,0,0,0,2,0,0,5,0,0,0,0,0,5,3,0,0,0,0,0,5,0,0,5,0,5,0,0,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0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,0,0,0,0,0,0,0,0,0,4,0,0,0,0,0,0,4,0,0,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,6,0,4,0,0,4,0,0,3,0,0,4,0,3,5,0,0,0,0,0,0,0,3,0,5,0,0,0,0,0,0,0,5,5,0,0,0,0,6,0,0,4,0,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,6,0,0,0,0,0,3,0,0,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,6,0,0,0,0,0,0,0,0,6,0,1,};
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n;
        scanf("%d",&n);
        if(n<=1000)
        {
            if(res[n])
                printf("%d\n",res[n]);
            else
                printf("-1\n");
            continue;
        }
        int sum = 0,r;
        while(n)
        {
            r= n%10;
            sum+=r*r;
            n/=10;
        }
        if(sum==1)
        {
            printf("1\n");
        }
        else{
            if(res[sum])
                printf("%d\n",res[sum]+1);
            else
                printf("-1\n");
        }
    }
    return 0;
}