0% found this document useful (0 votes)
75 views8 pages

Juspay

The document contains three JavaScript and three Python coding problems that involve reading input, processing data, and outputting results. The first problem focuses on simulating machine maintenance to achieve a production goal, the second deals with event processing and fee management along paths, and the third counts critical blocks in a grid based on neighborhood connectivity. Each problem includes detailed code implementations for handling the respective logic.

Uploaded by

Suraj Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views8 pages

Juspay

The document contains three JavaScript and three Python coding problems that involve reading input, processing data, and outputting results. The first problem focuses on simulating machine maintenance to achieve a production goal, the second deals with event processing and fee management along paths, and the third counts critical blocks in a grid based on neighborhood connectivity. Each problem includes detailed code implementations for handling the respective logic.

Uploaded by

Suraj Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

JAVASCRIPT​


QUE – 1

const readline = require('readline');

const rl = readline.createInterface({ input: process.stdin, output: process.stdout });


let inputLines = [];

rl.on('line', (line) => inputLines.push(line)).on('close', () => {


const [P, n] = inputLines[0].split(' ').map(Number);
const o = inputLines[1].split(' ').map(Number);
const c = inputLines[2].split(' ').map(Number);

const heap = o.map((output, i) => ({ output, maintenanceDays: c[i] }))


.sort((a, b) => b.output - a.output); // Max-heap simulation

let totalOutput = 0, days = 0;

while (totalOutput < P) {


days++;
if (heap.length > 0) {
const machine = heap.shift(); // Get the machine with the highest output
totalOutput += machine.output;
machine.maintenanceDays--; // Simulate maintenance
if (machine.maintenanceDays > 0) heap.push(machine); // Re-add if
maintenance is ongoing
heap.sort((a, b) => b.output - a.output); // Re-sort to maintain max-heap
}
}

console.log(days);
});

—-----------------------------------
QUE — 2

const readline = require('readline');

const rl = readline.createInterface({ input: process.stdin, output: process.stdout });


let q, events = [], lineCount = 0;

rl.on('line', (line) => {


if (lineCount === 0) q = +line;
else events.push(line.trim().split(' ').map(Number));
if (++lineCount === q + 1) rl.close(), processEvents();
});

function processEvents() {
const feeMap = new Map();

for (const [type, a, b, x] of events) {


const path = getPath(a, b);
if (type === 1) {
for (let i = 0; i < path.length - 1; i++) {
const key = path[i] < path[i + 1] ? `${path[i]}-${path[i + 1]}` : `${path[i +
1]}-${path[i]}`;
feeMap.set(key, (feeMap.get(key) || 0) + x);
}
} else if (type === 2) {
let totalCost = 0;
for (let i = 0; i < path.length - 1; i++) {
const key = path[i] < path[i + 1] ? `${path[i]}-${path[i + 1]}` : `${path[i +
1]}-${path[i]}`;
totalCost += feeMap.get(key) || 0;
}
console.log(totalCost);
}
}
}

function getPath(a, b) {
const pathA = [], pathB = [];
while (a !== b) {
if (a > b) pathA.push(a), a = Math.floor(a / 2);
else pathB.push(b), b = Math.floor(b / 2);
}
pathA.push(a);
return pathA.concat(pathB.reverse());
}

—-------------------------------------------
QUE — 3

const readline = require('readline');

const rl = readline.createInterface({ input: process.stdin, output: process.stdout });


let n, grid = [], lineCount = 0;

rl.on('line', (line) => {


if (lineCount === 0) n = +line;
else grid.push(line.trim());
if (++lineCount === 3) rl.close(), processGrid();
});

function processGrid() {
const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
let criticalBlocks = 0;

function dfs(i, j) {
if (i < 0 || i >= 2 || j < 0 || j >= n || grid[i][j] === 'x' || visited[i][j]) return;
visited[i][j] = true;
for (const [dx, dy] of directions) dfs(i + dx, j + dy);
}

function countNeighborhoods() {
let count = 0;
visited.forEach(row => row.fill(false));
for (let i = 0; i < 2; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === '.' && !visited[i][j]) {
dfs(i, j);
count++;
}
}
}
return count;
}

const visited = new Array(2).fill().map(() => new Array(n).fill(false));


for (let i = 0; i < 2; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === '.') {
grid[i] = grid[i].substring(0, j) + 'x' + grid[i].substring(j + 1);
if (countNeighborhoods() === 3) criticalBlocks++;
grid[i] = grid[i].substring(0, j) + '.' + grid[i].substring(j + 1);
}
}
}

console.log(criticalBlocks);
}

—-------------------------------------


– – PYTHON – –

1 — Python

import sys
import heapq

def main():
input = sys.stdin.read
data = input().split()

P = int(data[0])
n = int(data[1])

o = list(map(int, data[2:2+n]))
c = list(map(int, data[2+n:2+2*n]))

# Max heap to store available machines


heap = []
for i in range(n):
heapq.heappush(heap, (-o[i], c[i]))

total_output = 0
days = 0

while total_output < P:


days += 1
if heap:
output, maintenance_days = heapq.heappop(heap)
output = -output
total_output += output
heapq.heappush(heap, (-output, maintenance_days))
else:
# All machines are under maintenance
continue

# Check if any machines are due to come back from maintenance


for i in range(len(heap)):
if heap[i][1] == days:
heapq.heappush(heap, heap[i])

print(days)

if __name__ == "__main__":
main()

—------------------------ —

2 — Python

import sys

def get_path(a, b):


path_a, path_b = [], []
while a != b:
if a > b:
path_a.append(a)
a //= 2
else:
path_b.append(b)
b //= 2
path_a.append(a)
return path_a + path_b[::-1]

def get_key(u, v):


return (min(u, v), max(u, v))

def process_events(events):
fee_map = {}

for event in events:


type_, a, b = event[:3]

if type_ == 1:
x = event[3]
path = get_path(a, b)
for i in range(len(path) - 1):
key = get_key(path[i], path[i + 1])
fee_map[key] = fee_map.get(key, 0) + x
elif type_ == 2:
path = get_path(a, b)
total_cost = sum(fee_map.get(get_key(path[i], path[i + 1]), 0) for i in
range(len(path) - 1))
print(total_cost)

if __name__ == "__main__":
input_data = sys.stdin.read().splitlines()
q = int(input_data[0])
events = [list(map(int, line.split())) for line in input_data[1:q + 1]]
process_events(events)

—------------------------ —

3 — Python
def main():
import sys
input = sys.stdin.read
data = input().splitlines()

n = int(data[0])
grid = [data[1].strip(), data[2].strip()]

directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]


critical_blocks = 0

def dfs(i, j):


if i < 0 or i >= 2 or j < 0 or j >= n or grid[i][j] == 'x' or visited[i][j]:
return
visited[i][j] = True
for dx, dy in directions:
dfs(i + dx, j + dy)

def count_neighborhoods():
count = 0
for i in range(2):
for j in range(n):
if grid[i][j] == '.' and not visited[i][j]:
dfs(i, j)
count += 1
return count

for i in range(2):
for j in range(n):
if grid[i][j] == '.':
# Temporarily block the current cell
grid[i] = grid[i][:j] + 'x' + grid[i][j+1:]
visited = [[False] * n for _ in range(2)]
neighborhoods = count_neighborhoods()
if neighborhoods == 3:
critical_blocks += 1
# Restore the current cell
grid[i] = grid[i][:j] + '.' + grid[i][j+1:]

print(critical_blocks)

if __name__ == "__main__":
main()
—------------------------ —

You might also like