Problem Description: Given 2*N stones of N different colors, where there exists exactly 2 stones of each color, you need to arrange these stones in some order on a table. You may consider the table as an infinite 2D plane. The stones need to be placed under some restrictions : You can place a stone of color X, at a coordinate (X, Y) such that Y is not equal to X, and there exist 2 stones of color Y. In short consider you place a stone of color i at co-ordinate (X, Y). Here, it is necessary that (i=X) , (i!=Y) there exist some other stones of color equal to Y.
C Program


#include<stdio.h>

#include<math.h>

#include<stdlib.h>

int cmp(const void *a, const void *b){

    long long x=*(long long*)a, y=*(long long*)b;

    return (x>y)-(x<y);

}

int main(){

    int t;

    scanf("%d",&t);

    while(t--){

        int n,m,i;

        scanf("%d %d",&n,&m);

        long long a[100005];

        for(i=0;i<n;i++) scanf("%lld",&a[i]);

        qsort(a,n,sizeof(long long),cmp);

        if(a[0]>a[1]){ long long tmp=a[0];a[0]=a[1];a[1]=tmp; }

        /* Extract the two key boundary gaps using a loop of 2 */

        double gaps[2];

        for(i=0;i<2;i++){

            gaps[i] = (i==0) ? (double)(a[1]-a[0]) : (double)(a[n-1]-a[n-2]);

        }

        double D = (double)(a[n-1]-a[0]);

        double perim = 4.0*D - (2.0-sqrt(2.0))*(gaps[0]+gaps[1]);

        long long cost = (long long)ceil(perim) * (long long)m;

        printf("%lld\n",cost);

    }

    return 0;

}