Find maximum distance between any city and station | C ++ program to calculate the maximum distance between any city and its nearest station ; Function to calculate the maximum distance between any city and its nearest station ; Initialize boolean list ; Assign True to cities containing station ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaxDistance ( int numOfCities , int station [ ] , int n ) { bool hasStation [ numOfCities + 1 ] = { false } ; for ( int city = 0 ; city < n ; city ++ ) { hasStation [ station [ city ] ] = true ; } int dist = 0 ; int maxDist = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { maxDist = min ( station [ i ] , maxDist ) ; } for ( int city = 0 ; city < numOfCities ; city ++ ) { if ( hasStation [ city ] == true ) { maxDist = max ( ( dist + 1 ) / 2 , maxDist ) ; dist = 0 ; } else dist += 1 ; } return max ( maxDist , dist ) ; } int main ( ) { int numOfCities = 6 ; int station [ ] = { 3 , 1 } ; int n = sizeof ( station ) / sizeof ( station [ 0 ] ) ; cout << " Max ▁ Distance : " << findMaxDistance ( numOfCities , station , n ) ; }