Friday, 2 May 2014

Dijkstra Application

In the kingdom of NPLand, there are a number of cities. One of them is the capital. Cities are connected to each other through straight roads. Every year a single person from each city gets a chance to work in the capital. The King  organizes a competition every year. The rules are as follows:

1. The candidates will start running from their cities. (at the same times)
2. The entry into the capital will be permitted only for a fixed amount of time from when they all start running.
3. Whoever can enter the capital during that  fixed time will surely be permitted to work there.

Given the connections and the distances between the cities and the capital, the aim is to write a program to find out how many candidates can work in the capital.  In designing the program you can assume that the candidates will find a route so that they can get to the capital before the entry closes, if there is one.  

Note that all the cities are numbered from 0 to V-1.

Input: 
First line will contain the number of cities (V),number of roads (E) and time for which gate will be open (T).
E lines will follow, each containing 3 integers in the format:
city1 city2 t
where, city1 and city2 are the two cities having a road between them and it takes time t to go from one city to another. Note that all the roads are bidirectional and the city numbered 0 is the capital city.

Output:
A single integer representing number of candidates that can work in the capital

Constraints: 
1<=V<=100
1<=E<=100
1<=t<=100






#include <stdio.h>
#include <limits.h>
#include<stdlib.h>
int SSSP(int **gr, int s,int V,int T)
{
    int count=0,i,j,k;
    for (i = 0; i < V; i++)
    {
      for (j = 0; j < V; j++)
   {
           if(gr[i][j]>100 || gr[i][j]<1)
            gr[i][j]=9999;
          }
    }
    for (i = 0; i < V; i++)
    {
      for (j = 0; j < V; j++)
   {
           for (k = 0; k < V; k++)
    {
            if (gr[j][k] > gr[j][i] + gr[i][k])
     {
              gr[j][k] = gr[j][i] + gr[i][k];
            }
           }
          }
    }
    gr[s][s]=0;
    for (i = 0; i < V; i++)
    {
     if(gr[i][s]<=T)
  count++;
    }
    return count;
}
int main()
{
    int V,E,T;
    int **graph;
    scanf("%d %d %d",&V,&E,&T);
    graph = (int **)malloc(sizeof(int *)*V);
    int i=0;
    for(i=0;i<V;i++)
        graph[i] = (int *)malloc(sizeof(int)*V);
    for(i=0;i<E;i++)
    {
        int s,d,w;
        scanf("%d%d%d",&s,&d,&w);
        graph[s][d] = w;
        graph[d][s] = w;
    }
    printf("%d",SSSP(graph, 0,V,T));
    return 0;
}

No comments: