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, December 15, 2013

BAISED - Biased Standings

below given code is for baised spoj or baised standing.
Below given solution is (n+nlogn);
#include<stdio.h>
void merge(long long A[],long long low,long long mid,long long high,long long n)
{
 long long i,l,m,k,temp[n];
 i=low;m=mid+1;l=low;
 while(l<=mid && m<=high)
 {
        if(A[l]<=A[m])
        {
         temp[i]=A[l];
         i++;l++;
        }
        else
        {
         temp[i]=A[m];
         m++;i++;
        }
 }
 if(l>mid)
 {
        for(k=m;k<=high;k++){
         temp[i]=A[k];
         i++;
        }
 }
 else
 {
        for(k=l;k<=mid;k++)
        {
         temp[i]=A[k];
         i++;
        }
 }
 for(k=low;k<=high;k++)
        A[k]=temp[k];
}
void partition(long long A[],long long LB,long long UB,long long N)
{
 long long mid;
 if(LB<UB)
 {
        mid=(UB+LB)/2;
        partition(A,LB,mid,N);
        partition(A,mid+1,UB,N);
        merge(A,LB,mid,UB,N);
 }
}
int main()
{
 int t;
 scanf("%d",&t);
 while(t--)
 {
        long long N,i;
        scanf("%lld",&N);
        char NAME[10000];
        long long P_R[N],SUM=0;
        for(i=0;i<N;i++)
                scanf("%s%lld",NAME,&P_R[i]);
        partition(P_R,0,N-1,N);
        for(i=0;i<N;i++)
        {
         if((i+1)-P_R[i]<0)
                SUM=SUM+((-1)*((i+1)-P_R[i]));
         else
                SUM=SUM+((i+1)-P_R[i]);
        }
        printf("%lld\n",SUM);
 }
 return 0;
}



Below given solution is approx. O(n);
#include <bits/stdc++.h>
using namespace std;
#define LL long long
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        char name[1000];
        int n,temp,pos=0;
        LL sum=0;
        scanf("%d ",&n);
        int *arr;
        arr = (int *)calloc(n+9,sizeof(int));
        for(int i=0;i<n;i++)
        {
            scanf("%s%d",name,&temp);
            arr[temp]++;
        }
        for(int i=1;i<=n;i++)
        {
            if(arr[i]){
                temp=pos+1;
                pos+=arr[i];
                while(temp<=pos)
                {
                    sum+=(temp-i)<0?-1*(temp-i):(temp-i);
                    temp++;
                }
                if(pos==n)
                    break;
            }
        }
        printf("%lld\n",sum);
    }
    return 0;
}