Hackerrank Gridland Metro Solution
.MathJax_SVG_Display {text-align: center; margin: 1em 0em; position: relative; display: block!important; text-indent: 0; max-width: none; max-height: none; min-width: 0; min-height: 0; width: 100%} .MathJax_SVG .MJX-monospace {font-family: monospace} .MathJax_SVG .MJX-sans-serif {font-family: sans-serif} .MathJax_SVG {display: inline; font-style: normal; font-weight: normal; line-height: normal; font-size: 100%; font-size-adjust: none; text-indent: 0; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; word-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0; min-height: 0; border: 0; padding: 0; margin: 0} .MathJax_SVG * {transition: none; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none} .mjx-svg-href {fill: blue; stroke: blue} .MathJax_SVG_LineBox {display: table!important} .MathJax_SVG_LineBox span {display: table-cell!important; width: 10000em!important; min-width: 0; max-width: none; padding: 0; border: 0; margin: 0}
The city of Gridland is represented as an matrix where the rows are numbered from to and the columns are numbered from to .
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.
For example, if Gridland's data is the following:k = 3r c1 c21 1 42 2 43 1 24 2 3 It yields the following map:
In this case, there are five open cells (red) where lampposts can be placed.
Function Description
Complete the gridlandMetro function in the editor below. It should return an integer that denotes the number of cells where lampposts can be installed.
gridlandMetro has the following parameter(s):
- n: an integer, the number of rows in Gridland
- m: an integer, the number of columns in Gridland
- k: an integer, the number of tracks
- track: a 2 dimensional array of integers where each element contains integers that represent
Input Format.MathJax_SVG_Display {text-align: center; margin: 1em 0em; position: relative; display: block!important; text-indent: 0; max-width: none; max-height: none; min-width: 0; min-height: 0; width: 100%} .MathJax_SVG .MJX-monospace {font-family: monospace} .MathJax_SVG .MJX-sans-serif {font-family: sans-serif} .MathJax_SVG {display: inline; font-style: normal; font-weight: normal; line-height: normal; font-size: 100%; font-size-adjust: none; text-indent: 0; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; word-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0; min-height: 0; border: 0; padding: 0; margin: 0} .MathJax_SVG * {transition: none; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none} .mjx-svg-href {fill: blue; stroke: blue} .MathJax_SVG_LineBox {display: table!important} .MathJax_SVG_LineBox span {display: table-cell!important; width: 10000em!important; min-width: 0; max-width: none; padding: 0; border: 0; margin: 0}
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.
Constraints.MathJax_SVG_Display {text-align: center; margin: 1em 0em; position: relative; display: block!important; text-indent: 0; max-width: none; max-height: none; min-width: 0; min-height: 0; width: 100%} .MathJax_SVG .MJX-monospace {font-family: monospace} .MathJax_SVG .MJX-sans-serif {font-family: sans-serif} .MathJax_SVG {display: inline; font-style: normal; font-weight: normal; line-height: normal; font-size: 100%; font-size-adjust: none; text-indent: 0; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; word-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0; min-height: 0; border: 0; padding: 0; margin: 0} .MathJax_SVG * {transition: none; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none} .mjx-svg-href {fill: blue; stroke: blue}
Output Format.MathJax_SVG_Display {text-align: center; margin: 1em 0em; position: relative; display: block!important; text-indent: 0; max-width: none; max-height: none; min-width: 0; min-height: 0; width: 100%} .MathJax_SVG .MJX-monospace {font-family: monospace} .MathJax_SVG .MJX-sans-serif {font-family: sans-serif} .MathJax_SVG {display: inline; font-style: normal; font-weight: normal; line-height: normal; font-size: 100%; font-size-adjust: none; text-indent: 0; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; word-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0; min-height: 0; border: 0; padding: 0; margin: 0} .MathJax_SVG * {transition: none; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none} .mjx-svg-href {fill: blue; stroke: blue}
Print a single integer denoting the number of cells where the mayor can install lampposts.
Sample Input.MathJax_SVG_Display {text-align: center; margin: 1em 0em; position: relative; display: block!important; text-indent: 0; max-width: none; max-height: none; min-width: 0; min-height: 0; width: 100%} .MathJax_SVG .MJX-monospace {font-family: monospace} .MathJax_SVG .MJX-sans-serif {font-family: sans-serif} .MathJax_SVG {display: inline; font-style: normal; font-weight: normal; line-height: normal; font-size: 100%; font-size-adjust: none; text-indent: 0; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; word-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0; min-height: 0; border: 0; padding: 0; margin: 0} .MathJax_SVG * {transition: none; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none} .mjx-svg-href {fill: blue; stroke: blue}
4 4 3
2 2 3
3 1 4
4 4 4
Sample Output.MathJax_SVG_Display {text-align: center; margin: 1em 0em; position: relative; display: block!important; text-indent: 0; max-width: none; max-height: none; min-width: 0; min-height: 0; width: 100%} .MathJax_SVG .MJX-monospace {font-family: monospace} .MathJax_SVG .MJX-sans-serif {font-family: sans-serif} .MathJax_SVG {display: inline; font-style: normal; font-weight: normal; line-height: normal; font-size: 100%; font-size-adjust: none; text-indent: 0; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; word-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0; min-height: 0; border: 0; padding: 0; margin: 0} .MathJax_SVG * {transition: none; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none} .mjx-svg-href {fill: blue; stroke: blue}
9
Explanation.MathJax_SVG_Display {text-align: center; margin: 1em 0em; position: relative; display: block!important; text-indent: 0; max-width: none; max-height: none; min-width: 0; min-height: 0; width: 100%} .MathJax_SVG .MJX-monospace {font-family: monospace} .MathJax_SVG .MJX-sans-serif {font-family: sans-serif} .MathJax_SVG {display: inline; font-style: normal; font-weight: normal; line-height: normal; font-size: 100%; font-size-adjust: none; text-indent: 0; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; word-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0; min-height: 0; border: 0; padding: 0; margin: 0} .MathJax_SVG * {transition: none; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none} .mjx-svg-href {fill: blue; stroke: blue} .MathJax_SVG_LineBox {display: table!important} .MathJax_SVG_LineBox span {display: table-cell!important; width: 10000em!important; min-width: 0; max-width: none; padding: 0; border: 0; margin: 0}
In the diagram above, the yellow cells denote the first train track, green denotes the second, and blue denotes the third. Lampposts can be placed in any of the nine red cells.
Solution in java8
Approach 1.
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int row = in.nextInt(),
column = in.nextInt();
int matrix[][] = new int[row][column];
int trains = in.nextInt();
for (int i=0; i<trains; i++) {
int r = in.nextInt()-1;
int c1 = in.nextInt();
int c2 = in.nextInt();
for (int t=Math.min(c1,c2)-1; t<Math.max(c1,c2); t++) {
matrix[r][t] = 1;
}
}
int counter = 0;
for (int i=0; i<row; i++)
for(int j=0; j<column; j++)
if(matrix[i][j] == 0) counter ++;
System.out.println(counter);
}
}
Approach 2.
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n= in.nextInt();
int m = in.nextInt();
int k =in.nextInt(); int a[][] = new int[n][m];
for(int times=0;times<k;times++)
{
int row = in.nextInt();
int c1= in.nextInt();
int c2= in.nextInt();
row = row-1;c1=c1-1;c2=c2-1;
for(int i =c1;i<=c2;i++)
{
a[row][i]++;
}
}
int z=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(a[i][j] ==0)
{
z++;
}
}
}
System.out.println(z);
}
}
Approach 3.
import java.util.*;
public class GridLandMetro {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int[][] city = new int[n][m];
List<Integer> rows = new ArrayList<Integer>(k);
List<Integer> starts = new ArrayList<Integer>(k);
List<Integer> ends = new ArrayList<Integer>(k);
for (int i = 0; i < k; i++) {
rows.add(in.nextInt());
starts.add(in.nextInt());
ends.add(in.nextInt());
}
in.close();
int r = 0;
int c1 = 0;
int c2 = 0;
for (int i = 0; i < k; i++) {
r = rows.get(i);
c1 = starts.get(i);
c2 = ends.get(i);
for (int j = c1; j <= c2; j++) {
city[r - 1][j - 1] += 1;
}
}
int freeCells = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (city[i][j] == 0) {
freeCells++;
}
}
}
System.out.println(freeCells);
}
}
Solution in python3
Approach 1.
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the gridlandMetro function below.
def gridlandMetro(n, m, k, track):
spots = n*m
rows = dict()
for row in track:
r = row[0]
c1 = row[1]
c2 = row[2]
if r not in rows:
rows[r] = (c1, c2)
else:
rows[r] = (min(c1, rows[r][0]), max(c2, rows[r][1]))
for (c1, c2) in rows.values():
length = (c2 - c1) + 1
spots -= length
return spots
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nmk = input().split()
n = int(nmk[0])
m = int(nmk[1])
k = int(nmk[2])
track = []
for _ in range(k):
track.append(list(map(int, input().rstrip().split())))
result = gridlandMetro(n, m, k, track)
fptr.write(str(result) + '\n')
fptr.close()
Approach 2.
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the gridlandMetro function below.
def gridlandMetro(n, m, k, track):
c=n*m
x={}
for i in range(k):
r=track[i][0]
c1=track[i][1]
c2=track[i][2]
if r not in x:
c-=(c2-c1+1)
x[r]=(c1,c2)
else:
a=x[r]
p=min(a[0],c1)
q=max(a[1],c2)
c+=(a[1]-a[0]+1)
c-=(q-p+1)
x[r]=(p,q)
return c
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nmk = input().split()
n = int(nmk[0])
m = int(nmk[1])
k = int(nmk[2])
track = []
for _ in range(k):
track.append(list(map(int, input().rstrip().split())))
result = gridlandMetro(n, m, k, track)
fptr.write(str(result) + '\n')
fptr.close()
Approach 3.
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the gridlandMetro function below.
def gridlandMetro(n, m, k, track):
H = {}
for t in track:
tmp = H.get(t[0])
if tmp == None:
H[t[0]] = (min(t[1], t[2]), max(t[1], t[2]))
else:
start, end = min(tmp[0], tmp[1]), max(tmp[0], tmp[1])
if t[1] < start:
start = t[1]
if t[2] > end:
end = t[2]
H[t[0]] = (start, end)
total = n * m
for t in H.values():
total -= t[1] - t[0] + 1
return total
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nmk = input().split()
n = int(nmk[0])
m = int(nmk[1])
k = int(nmk[2])
track = []
for _ in range(k):
track.append(list(map(int, input().rstrip().split())))
result = gridlandMetro(n, m, k, track)
fptr.write(str(result) + '\n')
fptr.close()
Solution in cpp
Approach 1.
#include <iostream>
using namespace std;
int main() {
long long int r, c, t, i;
cin >> r >> c >> t;
long long int r1[t], c1[t], c2[t], count = 0;
for (i = 0; i < t; i++) {
cin >> r1[i] >> c1[i] >> c2[i];
}
for (i = 0; i < t; i++) {
for (int j = i + 1; j < t; j++) {
if (r1[i] == r1[j]) {
if (c1[i] >= c1[j] && c2[i] <= c2[j]) {
c1[i] = 0;
c2[i] = -1;
}
if (c1[i] <= c1[j] && c2[i] >= c1[j] && c2[i] <= c2[j]) {
c1[j] = c1[i];
c1[i] = 0;
c2[i] = -1;
}
if (c1[i] >= c1[j] && c1[i] <= c2[j] && c2[i] >= c2[j]) {
c2[j] = c2[i];
c1[i] = 0;
c2[i] = -1;
}
if (c1[i] <= c1[j] && c2[i] >= c2[j]) {
c1[j] = c1[i];
c2[j] = c2[i];
c1[i] = 0;
c2[i] = -1;
}
break;
}
}
}
for (i = 0; i < t; i++) {
count = count + c2[i] - c1[i] + 1;
}
cout << r * c - count;
}
Approach 2.
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long int ull;
typedef long long int ll;
#define rep(i, A, B) for (int i = A; i <= B; i++)
#define pb push_back
#define mp make_pair
#define S second
#define F first
#define all(c) (c).begin(), (c).end()
#define vectorIterate(v) for (auto it = v.begin(); it != v.end(); it++)
#define mod 1000000007
int main() {
ll n, m, k;
map<int, vector<pair<int, int>>> ma;
cin >> n >> m >> k;
while (k--) {
int r, c1, c2;
cin >> r >> c1 >> c2;
int count = 0;
// vector<pair<int,int> >::iterator it;
ma[r].pb(mp(c1, c2));
sort(ma[r].begin(), ma[r].end());
}
map<int, vector<pair<int, int>>>::iterator it;
ll sum = 0;
for (it = ma.begin(); it != ma.end(); it++) {
int x = 0;
for (int i = 0; i < it->S.size(); i++) {
if (it->S[i].S <= x)
continue;
if (it->S[i].F <= x)
it->S[i].F = x + 1;
sum += (it->S[i].S - it->S[i].F + 1);
x = it->S[i].S;
}
}
cout << (n * m - sum);
return 0;
}
Approach 3.
#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int>> merge(vector<pair<int, int>> &v) {
vector<pair<int, int>> merged;
if (v.size() != 0) {
sort(v.begin(), v.end());
}
stack<pair<int, int>> s;
int n = v.size();
s.push(v[0]);
for (int i = 1; i < n; i++) {
pair<int, int> top;
top = s.top();
if (v[i].first > top.second)
s.push(v[i]);
else if (top.second < v[i].second) { // if v[i].first <= top.second
top.second = v[i].second;
s.pop();
s.push(top);
}
}
while (!s.empty()) {
merged.push_back(s.top());
s.pop();
}
return merged;
}
int main() {
map<int, vector<pair<int, int>>> track;
int n, m, k;
cin >> n >> m >> k;
for (long i = 0; i < k; ++i) {
int r, c1, c2;
cin >> r >> c1 >> c2;
track[r].push_back(make_pair(c1, c2));
}
long totalcells = ((long)n) * ((long)m); // total no of cells in gridland
for (auto &node : track) { // merging the tracks of each row one by one
node.second = merge(node.second);
vector<pair<int, int>> tr = node.second;
// counting one by one by through each row, cells covered by tracks and
// subtracting them from totalcells
for (int i = 0; i < tr.size(); i++) {
totalcells -= ((long)tr[i].second) - ((long)tr[i].first) + 1;
}
}
cout << totalcells << endl;
return 0;
}