Gridland Metro
Problem Statement :
The city of Gridland is represented as an n x m matrix where the rows are numbered from 1 to n and the columns are numbered from 1 to m. Gridland has a network of train tracks that always run in straight horizontal lines along a row. In other words, the start and end points of a train track are and , where represents the row number, represents the starting column, and represents the ending column of the train track. The mayor of Gridland is surveying the city to determine the number of locations where lampposts can be placed. A lamppost can be placed in any cell that is not occupied by a train track. Given a map of Gridland and its train tracks, find and print the number of cells where the mayor can place lampposts. Note: A train track may overlap other train tracks within the same row. In this case, there are five open cells (red) where lampposts can be placed. Function Description Complete the gridlandMetro function in the editor below. gridlandMetro has the following parameter(s): int n:: the number of rows in Gridland int m:: the number of columns in Gridland int k:: the number of tracks track[k][3]: each element contains integers that represent , all 1-indexed Returns int: the number of cells where lampposts can be installed Input Format The first line contains three space-separated integers and , the number of rows, columns and tracks to be mapped. Each of the next lines contains three space-separated integers, and , the row number and the track column start and end.
Solution :
Solution in C :
In C++ :
#include <bits/stdc++.h>
using namespace std;
int main() {
long long h, w, K;
cin >> h >> w >> K;
long long ans = h * w;
map<int, vector<pair<int, int>>> mp;
for (int i = 0; i < K; i++) {
int y, l, r;
scanf("%d %d %d", &y, &l, &r);
mp[y].emplace_back(l, r);
}
for (auto &kv : mp) {
vector<pair<int, int>> evs;
for (auto p : kv.second) {
evs.emplace_back(p.first, 0);
evs.emplace_back(p.second, 1);
}
sort(evs.begin(), evs.end());
int cnt = 0;
int l = 0;
for (auto e : evs) {
if (e.second == 0) {
if (cnt == 0) l = e.first;
cnt++;
} else {
cnt--;
if (cnt == 0) ans -= e.first - l + 1;
}
}
}
cout << ans << endl;
}
In Java :
import java.util.*;
import java.awt.*;
public class Solution {
ArrayList<Point> locs;
public Solution(){
locs = new ArrayList<>();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long rows = in.nextInt(), cols = in.nextInt();
int tracks = in.nextInt();
ArrayList<Integer> check = new ArrayList<>();
HashMap<Integer, Solution> found = new HashMap<>();
for(int i = 0; i<tracks; i++){
int curRow = in.nextInt(), start = in.nextInt(), end = in.nextInt();
if(!found.containsKey(curRow)){
Solution sol = new Solution();
sol.locs.add(new Point(start,end));
check.add(curRow);
found.put(curRow,sol);
}else{
Solution sol = found.get(curRow);
sol.locs.add(new Point(start, end));
}
}
//Computing the total # of tracks - those of train tracks
long total = rows * cols;
for(int r : check){
// System.out.println(r);
Solution sol = found.get(r);
ArrayList<Point> myPoints = sol.locs;
Collections.sort(myPoints, new myComparator());
Point first = myPoints.get(0);
total -= (first.y - first.x+1);
int lastEnd = first.y+1;
for(int i = 1; i<myPoints.size(); i++){
Point curPoint = myPoints.get(i);
if(curPoint.y< lastEnd) continue;
int begin = Math.max(curPoint.x, lastEnd);
total -=(curPoint.y - begin + 1);
lastEnd = curPoint.y+1;
}
}
System.out.println(total);
}
}
class myComparator implements Comparator<Point>{
public int compare(Point p1, Point p2){
return p1.x - p2.x;
}
}
In C :
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
struct points
{
long int r;
long int c1;
long int c2;
};
typedef struct points points;
int comp(const void* a,const void* b)
{
points* a1=(points*)a;
points* b1=(points*)b;
if((a1->r)!=(b1->r))
return (a1->r)-(b1->r);
else
{
if((a1->c1)!=(b1->c1))
return (a1->c1)-(b1->c1);
else
return (a1->c2)-(b1->c2);
}
}
long int min(long int a,long int b)
{
if(a<b)
return a;
return b;
}
long int max(long int a,long int b)
{
if(a>b)
return a;
return b;
}
int main() {
long int n,m,r,c1,c2,temp,r_s,r_e;
int k,i,j;
scanf("%ld %ld %d",&n,&m,&k);
points p[k];
for(i=0;i<k;i++)
scanf("%ld %ld %ld",&p[i].r,&p[i].c1,&p[i].c2);
qsort(p,k,sizeof(p[0]),comp);
int visited[k];
memset(visited,0,sizeof(visited));
long long ans=n*m;
for(i=0;i<k;i++)
{
long int sub=0;
if(visited[i]==0){
for(j=i+1;j<k;j++)
{
if(p[i].r==p[j].r)
{
if(p[i].c2<p[j].c1)
{
sub+=p[i].c2-p[i].c1+1;
p[i].c1=p[j].c1;
p[i].c2=p[j].c2;
}
else
{
r_s=min(p[i].c1,p[j].c1);
r_e=max(p[i].c2,p[j].c2);
p[i].c1=r_s;
p[i].c2=r_e;
}
visited[j]=1;
}
else
break;
}
ans-=sub;
ans-=(p[i].c2-p[i].c1+1);
}
}
printf("%lld",ans);
return 0;
}
In Python3 :
from collections import defaultdict
n, m, k = map(int, input().split())
tracks = defaultdict(list)
for _ in range(k):
row, c1, c2 = map(int, input().split())
tracks[row].append((c1, -1))
tracks[row].append((c2 + 1, 1))
ans = 0
for row in tracks:
tracks[row].sort()
prev = tracks[row][0][0]
depth = 1
for event in tracks[row][1:]:
if depth > 0:
ans += (event[0] - prev)
depth -= event[1]
prev = event[0]
print(n * m - ans)
View More Similar Problems
Array-DS
An array is a type of data structure that stores elements of the same type in a contiguous block of memory. In an array, A, of size N, each memory location has some unique index, i (where 0<=i<N), that can be referenced as A[i] or Ai. Reverse an array of integers. Note: If you've already solved our C++ domain's Arrays Introduction challenge, you may want to skip this. Example: A=[1,2,3
View Solution →2D Array-DS
Given a 6*6 2D Array, arr: 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 An hourglass in A is a subset of values with indices falling in this pattern in arr's graphical representation: a b c d e f g There are 16 hourglasses in arr. An hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in arr, then print t
View Solution →Dynamic Array
Create a list, seqList, of n empty sequences, where each sequence is indexed from 0 to n-1. The elements within each of the n sequences also use 0-indexing. Create an integer, lastAnswer, and initialize it to 0. There are 2 types of queries that can be performed on the list of sequences: 1. Query: 1 x y a. Find the sequence, seq, at index ((x xor lastAnswer)%n) in seqList.
View Solution →Left Rotation
A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. Given an integer, d, rotate the array that many steps left and return the result. Example: d=2 arr=[1,2,3,4,5] After 2 rotations, arr'=[3,4,5,1,2]. Function Description: Complete the rotateLeft function in the editor below. rotateLeft has the following parameters: 1. int d
View Solution →Sparse Arrays
There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example: strings=['ab', 'ab', 'abc'] queries=['ab', 'abc', 'bc'] There are instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array, results=[2,1,0]. Fun
View Solution →Array Manipulation
Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu
View Solution →