Skip to content

Instantly share code, notes, and snippets.

@nahiyan
Created December 7, 2019 08:44
Show Gist options
  • Save nahiyan/bc749a49fd657cb1f8c3670c22335bc7 to your computer and use it in GitHub Desktop.
Save nahiyan/bc749a49fd657cb1f8c3670c22335bc7 to your computer and use it in GitHub Desktop.

Revisions

  1. nahiyan created this gist Dec 7, 2019.
    60 changes: 60 additions & 0 deletions main.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,60 @@
    #include <stdio.h>

    int main()
    {
    // Number of test cases
    int n;
    scanf("%d", &n);

    // Minimum distances
    int distances[n];

    // Loop through test cases
    int i;
    for (i = 0; i < n; i++)
    {
    // Number of streets
    int m;
    scanf("%d", &m);

    // Streets
    int streets[m];

    // Loop through streets
    int j;
    for (j = 0; j < m; j++)
    {
    scanf("%d", &streets[j]);
    }

    // Calculate median
    int median;
    if (m % 2 == 0)
    { // even
    median = (streets[(m / 2) - 1] + streets[(m / 2)]) / 2;
    }
    else
    { // odd
    median = streets[(m / 2)];
    }

    // Calculate distance from median and all the streets
    distances[i] = 0; // initiate the distance with 0

    for (j = 0; j < m; j++)
    {
    int distance = streets[j] - median;

    if (distance < 0)
    distances[i] += distance * -1;
    else
    distances[i] += distance;
    }
    }

    // Display minimum distances of each test case
    for (i = 0; i < n; i++)
    {
    printf("%d\n", distances[i]);
    }
    }