Tuesday, March 5, 2013

KingdomConnectivity

It has been a prosperous year for King Charles and he is rapidly expanding 
his kingdom.A beautiful new kingdom has been recently constructed and in this 
kingdom there are many cities connected by a number of one-way roads.
Two cities may be directly connected by more than one roads, this is to
 ensure high connectivity.

In this new kingdom King Charles has made one of the cities at his 
financial capital and one as warfare capital and he wants high 
connectivity between these two capitals.The connectivity of a pair of
 cities say city A and city B is defined as the number of different
 paths from city A to city B. A path may use a road more than once
 if possible. Two paths are considered different if they do not 
use exactly the same sequence of roads.

There are N cities numbered 1 to N in the new kingdom and M one-way roads
 . City 1 is the monetary capital and city N is the warfare capital.

You being one of the best programmers in new kingdom need to answer the
connectivity of financial capital and warfare capital ,
i.e number of different paths from city 1 to city N.

Input Description:

First line contains two integers N and M.

Then follow M lines ,each having two integers say x and y, 1<=x,y<=N ,
 indicating there is a road from city x to city y.

Output Description:

Print the number of different paths from 
city 1 to city N modulo 1,000,000,000(10^9).
If there are infinitely many different paths 
print "INFINITE PATHS"(quotes are for clarity).

Sample Input:

5 5
1 2
2 4
2 3
3 4
4 5

Sample Output:

2

Sample Input:

5 5
1 2
4 2
2 3
3 4
4 5

Sample Output:

INFINITE PATHS

Constraints:

2<=N<=10,000(10^4)

1<=M<=1,00,000(10^5) 

Two cities may be connected by more than two roads and in that case
those roads are to be considered different for counting distinct paths
 
/*
 *  KingdomConnectivity.c
 *  InterviewStreet
 *
 *  Created by Kyle Donnelly on 12/16/12.
 *
 *  Recursively finds the number of paths across a directed graph.
 *
 * Inputs:
 *  Number of cities and roads.
 *  Two integers: city where the road starts and city where it
 ends (index 1).
 *  Two integers: City id (number) which is the monetary capital
 *       City id (number) which is the war 
capital.
 *       By default these would be 1 and N
 for interviewstreet.
 *
 * Outputs:
 *  Number of paths from city 1 to city N (modulo MOD_LIMIT).
 *
 * Base case:
 *  Current city is the destination, return 1.
 *
 * Recursive case:
 *  Current city is not destination
 *  add up the number of paths of each city this one has access to.
 *
 * This program forces you to stop once you reach the destination.
 *
 */


#include 
#include 
#include 

#define MOD_LIMIT 1000000000

typedef struct {
 unsigned int id;
 struct _list *children;
 unsigned int distance;
} graph;

typedef struct _list {
 struct _list *next;
 graph *g;
} list;

typedef enum {
 UNVISITED, VISITED, LOOPED
} status;

static status *visited;  // array of city statuses
static graph **cities;  // array of city pointers
static jmp_buf buf;   // for loops

/* push a graph into a list of graphs */
void push_graph (list **head, graph *g) {
 list *cur;
 if (*head == NULL) {
  cur = *head = malloc(sizeof(list));
 }
 else {
  for (cur = *head; cur->next != NULL; cur = cur->next);
  cur = cur->next = malloc(sizeof(list));
 }
 
 cur->g = g;
 cur->next = NULL;
}

unsigned int find_paths (graph *source, graph *destination) {
 unsigned int retval = 0;
 list *cur;
 
 if (source == destination) {
  /* Awesome, we made it */
  return 1;
 }
 
 if (visited[source->id - 1] == VISITED) {
  /*
   * Loop in graph!
   * Not sure if this city actually leads to destination though.
   * If not then we don't care.
   * Alert earlier paths.
   */
  visited[source->id - 1] = LOOPED;
  return 0;
 }
 
 if (source->distance != -1) {
  /* Already know how many from here */
  return source->distance;
 }
 
 /* Mark that we've gone through this city already */
 visited[source->id - 1] = VISITED;
 
 for (cur = source->children; cur != NULL; cur = cur->next) {
  /* Check how many paths there are for each child city */
  retval = (retval + find_paths(cur->g, destination)) % (MOD_LIMIT);
 }
 
 /* Store for future paths through this city */
 source->distance = retval;
 
 /* Mark that we're done with this city */
 if (visited[source->id - 1] == LOOPED) {
  /* One of the paths led back here! */
  if (retval > 0) {
   /* There is a loop on the way to the destination! */
   longjmp(buf, 1);
  }
  
  /* But this city didn't lead to the destination anyway */
 }
 visited[source->id - 1] = UNVISITED;
 
 return (retval);
}

int main() {
 unsigned int n, m, to, from, money, war;
 unsigned int num_paths;
 
 scanf("%u %u", &n, &m);
 
 cities = malloc(sizeof(graph *) * n);
 visited = malloc(sizeof(status) * n);
 
 for (unsigned int i=0; i  cities[i] = malloc(sizeof(graph));
  cities[i]->id = i+1;
  cities[i]->children = NULL;
  cities[i]->distance = -1;
  visited[i] = UNVISITED;
 }
 
 for (unsigned int i=0; i  scanf("%u %u", &from, &to);
  
  /* Add node to parent's children */
  push_graph(&(cities[from-1]->children), cities[to-1]);
 }
 
 scanf("%u %u", &money, &war);
 
 if (!(setjmp(buf))) {
  /* Try this */
  num_paths = find_paths(cities[money-1], cities[war-1]);
  printf("%u\n", num_paths);
 }
 else {
  /* If there are infinite paths just print that */
  printf("INFINITE PATHS\n");
 }
 
 return 0;
} 

StockMaximize

Your algorithms have become so good at predicting the market that you now know what the share price
 of Wooden Orange Toothpicks Inc. (WOT) will be for the next N days.

Each day, you can either buy one share of WOT, or sell any number of shares of WOT that you own. 
What is the maximum profit you can obtain with an optimum trading strategy?

Input

The first line contains the number of test cases T. T test cases follow:

The first line of each test case contains a number N. The next line contains N integers, denoting the 
predicted price of WOT shares for the next N days.

Output

Output T lines, containing the maximum profit which can be obtained for the corresponding test case.

Constraints

1 <= T <= 10
1 <= N <= 50000

All share prices are between 1 and 100000

Sample Input

3
3
5 3 2
3
1 2 100
4
1 3 1 2
Sample Output

0
197
3
Explanation

For the first case, you cannot obtain any profit because the share price never rises. 
For the second case, you can buy one share on the first two days, and sell both of them on the third day.
 
 
/*
 *  StockMax.c
 *  InterviewStreet
 *
 *  Created by Kyle Donnelly on 3/5/13.
 *
 * Pretty straightforward solution:
 *  Basically, you want to own as many shares as possible on the day
 *   that stock is worth the most
 *   Because any price you could have bought it for previously
 *   is less than it is now.
 *  After that day when it's worth the most, just repeat the process.
 *
 * We keep an array of prices
 *  and an array of indexes associated with the sorted price array
 * Step through those indexes in descending order
 *  Buy every day since the last peak in price
 *  simple formula: (this peak index - last peak index) * price of this peak
 *  then subtract the amount of money it would have cost to buy at all the earlier prices.
 *
 * Space complexity:
 *  We need two arrays of length 'n' --> O(n)
 *
 * Running time complexity:
 *  Sorting array of length 'n' with quicksort --> O(n*logn)
 *  Look through each index in decreasing order (look for highest peaks in remaining prediction)
 *   Step through each price until that peak --> O(n)
 *  so O(n*logn) overall, sorting is the bottleneck.
 *
 * Don't have to worry about the order peaks are sorted in if they have the same value
 *  selling everything or buying that share and selling it later have the exact same effect
 *
 */

#include 
#include 

typedef unsigned int uint;

/*
 * Permutes array idx so that the array indexers correspond
 *    to a sorted order of the array
 *    but the array is not actually changed.
 */
static void q_sort (uint *arr, uint *idx, uint beg, uint end) {
 if (end > beg + 1)
 {
  uint piv = arr[idx[(end+beg)/2]], l = beg, r = end-1;
  while (l <= r)
  {
   if (arr[idx[l]] > piv)
    l++;
   else if (arr[idx[r]] < piv)
    r--;
   else {
    uint t = idx[l];
    idx[l++] = idx[r];
    idx[r--] = t;
   }
  }
  q_sort(arr, idx, beg, r+1);
  q_sort(arr, idx, l, end);
 }
 return;
}

int main (void) {
 uint cases, days, *prices, *idx;
 uint best_price, last_index;
 
 scanf("%u", &cases);
 
 for (uint i=0; i  scanf("%u", &days);
  prices = malloc(sizeof(uint) * days);
  idx = malloc(sizeof(uint)*days);
  best_price = last_index = 0;
  
  for (uint j=0; j   scanf("%u", &(prices[j]));
   idx[j] = j;
  }
  
  q_sort(prices, idx, 0, days);
  
  for (uint j=0; j   if (idx[j] >= last_index) {
    best_price += prices[idx[j]] * (idx[j] - last_index);
    for (uint k=last_index; k     best_price -= prices[k];
    }
    last_index = idx[j] + 1;
   }
  }
  
  printf("%u\n", best_price);
  free(prices);
  free(idx);
 }
 
 return 0;
} 

pairs problem


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PairsDemo
{
    class Solution
    {
        static void Main(string[] args)
        {
            string input = Console.ReadLine();
            int N = Int32.Parse(input.Split(' ')[0]);
            long K = long.Parse(input.Split(' ')[1]);
            input = Console.ReadLine();
           
            long[] data = new long[N];
            string[] ds = input.Split(' ');
            for (int i = 0; i  K)
            {
                for (int i = N - 1; i >= 0; i--)
                {

                    for (int j = i - 1; j >= 0; j--)
                    {
                       
                        if (data[i] - data[j] == K)
                        {
                            result++;

                        }
                        else if (data[i] - data[j] > K)
                        {

                            break;
                        }
                    }
                }
            }

            Console.WriteLine(result);

        }
    }
}

Flowers problem

Problem:
You and your K-1 friends want to buy N flowers. Flower number i has host ci. Unfortunately the seller does not like a customer to buy a lot of flowers, so he tries to change the price of flowers for customer who had bought flowers before. More precisely if a customer has already bought x flowers, he should pay (x+1)*ci dollars to buy flower number i.
You and your K-1 firends want to buy all N flowers in such a way that you spend the as few money as possible.

Input:
The first line of input contains two integers N and K.
next line contains N positive integers c1,c2,…,cN respectively.

Output:
Print the minimum amount of money you (and your friends) have to pay in order to buy all n flowers.
Sample onput :
3 3
2 5 6

Sample output :
13
Explanation :
In the example each of you and your friends should buy one flower. in this case you have to pay 13 dollars.

Constraint : 1 less than or equal to N,K less than or equal to 100 and each ci is not more than 100,000



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FlowersDemo
{
    class Solution
    {
        static void Main(String[] args)
        {
            int N, K;
            string NK = Console.ReadLine();
            string[] NandK = NK.Split(new Char[] { ' ', '\t', '\n' });
            N = Convert.ToInt32(NandK[0]);
            K = Convert.ToInt32(NandK[1]);

            int[] C = new int[N];

            string numbers = Console.ReadLine();
            string[] split = numbers.Split(new Char[] { ' ', '\t', '\n' });
           
            double result = 0;
            int i = 0;
            foreach (string s in split)
            {
                if (s.Trim() != "")
                {
                    C[i++] = Convert.ToInt32(s);
                    if (N == K)
                        result += Convert.ToInt32(s);
                }
            }
            if (N != K)
            {
                Array.Sort(C);
                int counter = 0;
                for (int a = N - 1; a >= 0; a--)
                {
                    result += Math.Ceiling((double)(counter/K)+1) * C[a];
                    counter++;
                }

            }

            Console.WriteLine((int)result);
        }
    }
}


 

candies problem

Problem:
Alice is a kindergarden teacher. She wants to give some candies to the children in her class. All the children sit in a line and each of them has a rating score according to his or her usual performance. Alice wants to give at least 1 candy for each child.Children get jealous of their immediate neighbors, so if two children sit next to each other then the one with the higher rating must get more candies. Alice wants to save money, so she wants to minimize the total number of candies.
Input
The first line of the input is an integer N, the number of children in Alice’s class. Each of the following N lines contains an integer indicates the rating of each child.
Ouput
Output a single line containing the minimum number of candies Alice must give.
Sample Input
3
1
2
2

Sample Ouput
4
Explanation
The number of candies Alice must give are 1, 2 and 1.
Constraints:
N and the rating of each child are no larger than 10^5.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CandiesDemo
{
    class Solution
    {
        static void Main(string[] args)
        {
            int N = Int32.Parse(Console.ReadLine());
            int[] ranks=new int[N] ;
            int[] candi = new int[N];
            int results = 0;
            for (int i = 0; i < N; i++)
            {
                ranks[i] = Int32.Parse(Console.ReadLine());
                candi[i] = 1;
               
            }
            bool IsCompleted = false;
            while (!IsCompleted)
            {
                IsCompleted = true;
                for (int i = 0; i < N; i++)
                {
                    if (i == 0)
                    {
                        if (ranks[0] > ranks[1] && candi[0] <= candi[1])
                        {
                            candi[0] = candi[1] + 1;
                            IsCompleted = false;
                        }
                    }
                    else if (i == N - 1)
                    {
                        if (ranks[N - 1] > ranks[N - 2] && candi[N - 1] <= candi[N - 2])
                        {
                            candi[N - 1] = candi[N - 2] + 1;
                            IsCompleted = false;
                        }
                    }
                    else
                    {
                        if (ranks[i] > ranks[i - 1] && candi[i] <= candi[i - 1])
                        {
                            candi[i] = candi[i - 1] + 1;
                            IsCompleted = false;
                        }
                        else if (ranks[i] > ranks[i + 1] && candi[i] <= candi[i + 1])
                        {
                            candi[i] = candi[i + 1] + 1;
                            IsCompleted = false;
                        }
                    }
                }
            }
           
            for (int i = 0; i < N; i++)
            {
                results += candi[i];
            }

            Console.WriteLine(results);
                         
        }
    }
}
 

Picking Cards problem

Problem:
There are N cards on the table and each has a number between 0 and N. Let us denote the number on the ith card by ci. You want to pick up all the cards. The ith card can be picked up only if at least ci cards have been picked up before it. (As an example, if a card has a value of 3 on it, you can’t pick that card up unless you’ve already picked up 3 cards previously) In how many ways can all the cards be picked up?
Input:
The first line contains the number of test cases T. T test cases follow. Each case contains an integer N on the first line, followed by integers ci,…,cN on the second line.
Output:
Output T lines one corresponding to each test case containing the required answer for the corresponding test case. As the answers can be very big, output them modulo 1000000007.
Sample Input:
3
3
0 0 0
3
0 0 1
3
0 3 3
Sample Output:
6
4
0
Sample Explanations:
For the first case, the cards can be picked in any order, so there are 3! = 6 ways.
For the second case, the cards can be picked in 4 ways: {1,2,3}, {2,1,3}, {1,3,2}, {2,3,1}.
For the third case, no cards can be picked up after the first one, so there are 0 ways to pick up all cards.
Constraints:
1 <= T <= 10
1 <= N <= 50000
0 <= ci <= N


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Solution
{
    public static void Main(string[] args)
    {
        int T = Int32.Parse(Console.ReadLine());
        for (int i = 0; i < T; i++)
        {
            int N = Int32.Parse(Console.ReadLine());
            long result = 1;
            string[] s = Console.ReadLine().Split(' ');
            int[] input = new int[N];
            for (int k = 0; k < N; k++)
            {
               
                input[k] = Int32.Parse(s[k]);
            }
            Array.Sort(input);
            if (input[N - 1] >= N || input[0] != 0)
            {
                result = 0;
            }
            else
            {
                for (int j = N - 1; j >= 0; j--)
                {
                    if (input[j] > j)
                    {
                        result = 0;
                        break;
                    }
                    else
                    {
                        result = ((result) * ((j - input[j]) + 1)) % 1000000007;
                    }
                }

            }
            Console.WriteLine(result);
        }
    }
}

 

median problem

The median of M numbers is defined as the middle number after sorting them in order if M is odd or the average number of the middle 2 numbers (again after sorting) if M is even. You have an empty number list at first. Then you can add or remove some number from the list. For each add or remove operation, output the median of numbers in the list.
Example : For a set of m = 5 numbers, { 9, 2, 8, 4, 1 } the median is the third number in sorted set { 1, 2, 4, 8, 9 } which is 4. Similarly for set of m = 4, { 5, 2, 10, 4 }, the median is the average of second and the third element in the sorted set { 2, 4, 5, 10 } which is (4+5)/2 = 4.5
Input:
The first line is an integer n indicates the number of operations. Each of the next n lines is either “a x” or “r x” which indicates the operation is add or remove.
Output:
For each operation: If the operation is add output the median after adding x in a single line. If the operation is remove and the number x is not in the list, output “Wrong!” in a single line. If the operation is remove and the number x is in the list, output the median after deleting x in a single line. (if the result is an integer DO NOT output decimal point. And if the result is a double number , DO NOT output trailing 0s.)
Constraints:
0 < n <= 100,000
for each “a x” or “r x”, x will always be an integer which will fit in 32 bits (unsigned)
Sample Input:
7
r 1
a 1
a 2
a 1
r 1
r 2
r 1
Sample Output:
Wrong!
1
1.5
1
1.5
1
Wrong!
Note: As evident from the last line of the input, if after remove operation the list becomes empty you have to print “Wrong!” ( quotes are for clarity ).



using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
class Solution
{
    private static List list = new List();
    private static int count = 0;
    private static long min = long.MaxValue;
    private static long max = long.MinValue;
    private static long sum = 0;
    private static int mid = 0;
    private static int MedianIndex = 0;
    private static double MedianValue = 0;
    static void Main(String[] args)
    {
        int N = Convert.ToInt32(Console.ReadLine());
        int[] x = new int[N];
        string[] s = new string[N];
        string[] split = new string[2];
        for (int i = 0; i < N; i++)
        {
            split = Console.ReadLine().Split(new Char[] { ' ', '\t', '\n' });
            s[i] = split[0].Trim();
            x[i] = Convert.ToInt32(split[1].Trim());
        }
        for (int i = 0; i < N; i++)
        {
            if (s[i] == "a")
            {
                if (x[i] <= min)
                {
                    min = x[i];
                    list.Insert(0, x[i]);
                }
                else if (x[i] >= max)
                {
                    max = x[i];
                    list.Add(x[i]);
                }
                else
                {
                    if (x[i] > MedianValue)
                        list.Insert(ReturnIndex(x[i], MedianIndex, list.Count - 1), x[i]);
                    else
                        list.Insert(ReturnIndex(x[i], 0, MedianIndex), x[i]);

                }

                count++;
                PrintMedian();
            }
            else
            {
                int index = -1;
                if (count > 0)
                {
                    if (x[i] > MedianValue)
                    {
                        index = list.BinarySearch(MedianIndex, count - MedianIndex, x[i], null);
                    }
                    else
                    {
                        index = list.BinarySearch(0, MedianIndex + 1, x[i], null);
                    }
                }
                if (index < 0)
                    Console.WriteLine("Wrong!");
                else
                {
                    if (x[i] == min)
                        list.RemoveAt(0);
                    else if (x[i] == max)
                        list.RemoveAt(count - 1);
                    else
                    {
                        list.RemoveAt(index);
                    }
                    count--;
                    if (count == 0)
                    {
                        min = long.MaxValue;
                        max = long.MinValue;
                        Console.WriteLine("Wrong!");
                    }
                    else
                        PrintMedian();
                }

            }

        }
        Console.ReadKey();

    }
    private static int ReturnIndex(int item, int start, int end)
    {
        int i = start;
        int j = end;
        while (i <= j)
        {
            int midindex = (i + j) / 2;
            if (item > list[midindex])
            {
                i = midindex + 1;
            }
            else if (item < list[midindex])
                j = midindex - 1;
            else
            {
                return midindex;
            }
        }
        return i;
    }
    private static void PrintMedian()
    {

        if (count == 1)
        {
            MedianIndex = 0;
            MedianValue = list[0];
            min = list[0];
            max = list[0];
            Console.WriteLine(list[0]);
        }
        else
        {
            mid = count / 2;
            MedianIndex = mid;
            MedianValue = list[mid];
            if (count % 2 != 0)
                Console.WriteLine(list[mid]);
            else
            {
                sum = (long)list[mid] + list[mid - 1];
                if (sum % 2 == 0)
                {
                    Console.WriteLine(sum / 2);
                }
                else
                    Console.WriteLine(((double)sum) / 2);
            }
        }
    }
}
 

unfriendly numbers problem

Problem:
There is one friendly number and N unfriendly numbers. We want to find how many numbers are there which exactly divide the friendly number, but does not divide any of the unfriendly numbers.
Input Format:
The first line of input contains two numbers N and K seperated by spaces. N is the number of unfriendly numbers, K is the friendly number.
The second line of input contains N space separated unfriendly numbers.
Output Format:
Output the answer in a single line.
Constraints:
1 <= N <= 10^6
1 <= K <= 10^13
1 <= unfriendly numbers <= 10^18
Sample Input:
8 16
2 5 7 4 3 8 3 18
Sample Output:
1
Explanation :
Divisors of the given friendly number 16, are { 1, 2, 4, 8, 16 } and the unfriendly numbers are {2, 5, 7, 4, 3, 8, 3, 18}. Now 1 divides all unfriendly numbers, 2 divide 2, 4 divide 4, 8 divide 8 but 16 divides none of them. So only one number exists which divide the friendly number but does not divide any of the unfriendly numbers. So the answer is 1.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UnFriendlyDemo
{
    class Program
    {
        //private static int results = 0;
        private static bool IsDividesUnFrnd = false;
        private static List factors = new List();
        private static List gcd = new List();
        static void Main(string[] args)
        {
            string[] input = Console.ReadLine().Split(new char[] { ' ', '\t', '\n' });
            int N = Int32.Parse(input[0]);
            ulong K = ulong.Parse(input[1]);
            ulong[] UnFrndNumbers = new ulong[N];
            input = Console.ReadLine().Split(new char[] { ' ', '\t', '\n' });
            for (int i = 0; i< N; i++)
            {
                UnFrndNumbers[i] = ulong.Parse(input[i]);
                gcd.Add(GetGcd(K, UnFrndNumbers[i]));
            }
            //Array.Sort(UnFrndNumbers);

            List divisor = CalculateDivisors(K);
            var g=gcd.Distinct();
            foreach (var gd in g)
            {
                for (int j = divisor.Count - 1; j >= 0; j--)
                {
                    if (gd % divisor[j] == 0)
                        divisor.RemoveAt(j);
                }
            }
            Console.WriteLine(divisor.Count);
            Console.ReadKey();
        }

        private static List CalculateDivisors(ulong number)
        {
            factors = new List();
            for (ulong factor = 1; factor * factor<= number; factor++)
            {
                if (number % factor == 0)
                {
                    factors.Add(factor);
                    if (factor * factor != number)
                    {
                        factors.Add(number / factor);
                    }

                }
            }

            return factors;
        }

        public static ulong GetGcd(ulong a, ulong b)
        {
            while (b != 0)
            {
                ulong m = a % b;
                a = b;
                b = m;
            }
            return a;
        }



    }
}

 

meeting point problem

problem:
There is an infinite integer grid where N people live in N different houses. They decide to create a meeting point at one person’s house.
From any given cell, all 8 adjacent cells are reachable in 1 unit of time, e.g. (x,y) can be reached from (x-1,y+1) in one unit of time. Find a common meeting place which minimizes the combined travel time of everyone.
Input Format
N for N houses.
The following N lines will contain two integers for the x and y coordinate of the nth house.
Output Format
M for the minimum sum of all travel times when everyone meets at the best location.
Constraints
N <= 105
The absolute value of each co-ordinate in the input will be at most 109
HINT: Please use long long 64-bit integers;
Input #1
4
0 1
2 5
3 1
4 0
Output #1
8
Explanation
The houses will have a travel-sum of 11, 13, 8 or 10. 8 is the minimum.
Input #2
6
12 -14
-3 3
-14 7
-14 -3
2 -12
-1 -6
Output #2:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Solution
{

    static string[] input = new string[2];
    static void Main(string[] args)
    {

        long N = Int64.Parse(Console.ReadLine());
        long[] X = new long[N];
        long[] Y = new long[N];
        long results = 0;
        double avg_x = 0;
        double avg_y = 0;
        double min = 0;
        int point = 0;
        for (int c = 0; c        {
            input = Console.ReadLine().Split(' ');
            X[c] = long.Parse(input[0]);
            Y[c] = long.Parse(input[1]);
        }
        for (int i = 0; i        {
            avg_x += (double)X[i] / N;
            avg_y += (double)Y[i] / N;
        }

        min = Math.Sqrt(((avg_x - X[0]) * (avg_x - X[0])) + ((avg_y - Y[0]) * (avg_y - Y[0])));
        for (int i = 1; i < N; i++)
        {
            double diff = Math.Sqrt(((avg_x - X[i]) * (avg_x - X[i])) + ((avg_y - Y[i]) * (avg_y - Y[i])));
            if (diff             {
                min = diff;
                point = i;
            }
        }
        for (int i = 0; i        {
            results += Math.Max((Math.Abs(X[point] - X[i])), (Math.Abs(Y[point] - Y[i])));
        }
        Console.WriteLine(results);
    }
}

 

String Similarity

problem:
String Similarity (25 Points)

For two strings A and B, we define the similarity of the strings to be the length of the longest prefix common to both strings. For example, the similarity of strings “abc” and “abd” is 2, while the similarity of strings “aaa” and “aaab” is 3.
Calculate the sum of similarities of a string S with each of it’s suffixes.
Input:
The first line contains the number of test cases T. Each of the next T lines contains a string each.

Output:
Output T lines containing the answer for the corresponding test case.

Constraints:
1 <= T <= 10
The length of each string is at most 100000 and contains only lower case characters.

Sample Input:
2
ababaa
aa

Sample Output:
11
3

Explanation:
For the first case, the suffixes of the string are “ababaa”, “babaa”, “abaa”, “baa”, “aa” and “a”. The similarities of each of these strings with the string “ababaa” are 6,0,3,0,1,1 respectively. Thus the answer is 6 + 0 + 3 + 0 + 1 + 1 = 11.

For the second case, the answer is 2 + 1 = 3.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace StringRedDemo
{
    class Solution
    {
        static int finalLength = 0;
        static void Main(string[] args)
        {
            int totalInputs = int.Parse(Console.ReadLine());
            for (int i = 0; i             {
                string strToProcess = Console.ReadLine();
                int totalstrLength = strToProcess.Length;
                finalLength = totalstrLength;
                char[] masterarraychar = strToProcess.ToCharArray();
                for (int k = 1; k                {

                    if (masterarraychar[0] != masterarraychar[k])
                        continue;
                    matchlen(masterarraychar, k);

                }
                Console.WriteLine(finalLength);
            }
            Console.ReadKey();
        }
        private static void matchlen(char[] masterarraychar, int k)
        {
            for (int j = 0; j < masterarraychar.Length - k; j++)
            {
                if (masterarraychar[j + k] == masterarraychar[j])
                {
                    finalLength++;
                }
                else
                {
                    break;
                }
            }
        }

    }
}