0% found this document useful (0 votes)
27 views52 pages

D@C

Daa

Uploaded by

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

D@C

Daa

Uploaded by

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

//D@C

//Quick sort partition 1


----------------------------------
import java.io.*;
import java.util.*;
import java.util.stream.*;

class Result {

/*
* Complete the 'quickSort' function below.
*
* The function is expected to return an INTEGER_ARRAY.
* The function accepts INTEGER_ARRAY arr as parameter.
*/

public static List<Integer> quickSort(List<Integer> arr) {


quickSortHelper(arr, 0, arr.size() - 1);
return arr;
}

private static void quickSortHelper(List<Integer> arr, int low, int high) {


if (low < high) {
int pivotIndex = partition(arr, low, high);
quickSortHelper(arr, low, pivotIndex - 1);
quickSortHelper(arr, pivotIndex + 1, high);
}
}

private static int partition(List<Integer> arr, int low, int high) {


int pivot = arr.get(low);
int left = low + 1;
int right = high;

while (left <= right) {


while (left <= right && arr.get(left) <= pivot) {
left++;
}
while (left <= right && arr.get(right) > pivot) {
right--;
}
if (left < right) {
Collections.swap(arr, left, right);
}
}
Collections.swap(arr, low, right);
return right;
}
}

public class Solution {


public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new
FileWriter(System.getenv("OUTPUT_PATH")));

int n = Integer.parseInt(bufferedReader.readLine().trim());

List<Integer> arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$",


"").split(" "))
.map(Integer::parseInt)
.collect(Collectors.toList());

List<Integer> result = Result.quickSort(arr);

bufferedWriter.write(
result.stream()
.map(Object::toString)
.collect(Collectors.joining(" "))
+ "\n"
);

bufferedReader.close();
bufferedWriter.close();
}
}

----------------------------------------
//unique divide and conquer

import java.io.*;
import java.util.*;

public class Solution {


FastScanner in;
PrintWriter out;

void solve() {
int n = in.nextInt();
int p = in.nextInt();
int[][] c = new int[n + 1][n + 1];
c[0][0] = 1;
for (int i = 1; i <= n; i++) {
c[i][0] = 1;
for (int j = 1; j <= n; j++) {
c[i][j] = c[i - 1][j - 1] + c[i - 1][j];
if (c[i][j] >= p) {
c[i][j] -= p;
}
}
}
long[] dpSum = new long[n + 1];
long[] ans = new long[n + 1];
long[] dpBad = new long[n + 1];
dpSum[0] = 1;
for (int sz = 1; sz <= n; sz++) {
for (int big = (1 + sz) / 2; big < sz; big++) {
dpBad[sz] += dpSum[sz - 1 - big] * ans[big] % p * big % p
* c[sz - 1][big] % p;
}
dpBad[sz] %= p;
ans[sz] = (dpSum[sz - 1] - dpBad[sz] + p) * sz % p;
for (int size1 = 1; size1 <= sz; size1++) {
dpSum[sz] += ans[size1] * size1 % p * c[sz - 1][size1 - 1] % p
* dpSum[sz - size1] % p;
}
dpSum[sz] %= p;
}
out.println(ans[n]);
}

void run() {
try {
in = new FastScanner(new File("object.in"));
out = new PrintWriter(new File("object.out"));

solve();

out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

void runIO() {

in = new FastScanner(System.in);
out = new PrintWriter(System.out);

solve();

out.close();
}

class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}

String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}

boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}

int nextInt() {
return Integer.parseInt(next());
}

long nextLong() {
return Long.parseLong(next());
}

double nextDouble() {
return Double.parseDouble(next());
}
}

public static void main(String[] args) {


new Solution().runIO();
}
}

-----------------------------------------
//Maximum Subarray Sum

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

/*
* Complete the 'maximumSum' function below.
*
* The function is expected to return a LONG_INTEGER.
* The function accepts following parameters:
* 1. LONG_INTEGER_ARRAY a
* 2. LONG_INTEGER m
*/

public static long maximumSum(List<Long> a, long m) {


// Write your code here
int n = a.size();
long maxMod = 0;
TreeSet<Long> prefixSums = new TreeSet<>();
long currentPrefixSum = 0;

prefixSums.add(0L); // Base case for subarrays starting from index 0

for (long num : a) {


currentPrefixSum = (currentPrefixSum + num) % m;

// Find the smallest prefix sum that is greater than currentPrefixSum


Long higherPrefixSum = prefixSums.higher(currentPrefixSum);

// Check if this prefix sum results in a higher modulo value


if (higherPrefixSum != null) {
maxMod = Math.max(maxMod, (currentPrefixSum - higherPrefixSum + m)
% m);
}

// Check the current prefix sum itself


maxMod = Math.max(maxMod, currentPrefixSum);

// Add the current prefix sum to the set


prefixSums.add(currentPrefixSum);
}

return maxMod;

public class Solution {


public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new
FileWriter(System.getenv("OUTPUT_PATH")));

int q = Integer.parseInt(bufferedReader.readLine().trim());

IntStream.range(0, q).forEach(qItr -> {


try {
String[] firstMultipleInput =
bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");

int n = Integer.parseInt(firstMultipleInput[0]);

long m = Long.parseLong(firstMultipleInput[1]);

List<Long> a = Stream.of(bufferedReader.readLine().replaceAll("\\s+
$", "").split(" "))
.map(Long::parseLong)
.collect(toList());

long result = Result.maximumSum(a, m);

bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
});

bufferedReader.close();
bufferedWriter.close();
}
}
------------------------------------------------
//Number of rotations

import java.io.*;
import java.util.*;

public class Solution {

public static void main(String[] args) {


Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] arr=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
int ind=-1;
int mini=Integer.MAX_VALUE;
for(int i=0;i<n;i++)
{
if(arr[i]<mini)
{
mini=arr[i];
ind=i;
}
}
int res=n-ind;
if(res==n)
System.out.println(0);
else
System.out.println(res);
}
}

-------------------------------------------------
//inversion count 11

import java.io.*;
import java.util.*;

public class Solution {

// Function to count inversions using modified merge sort


public static long countInversions(int[] array) {
return mergeSortAndCount(array, 0, array.length - 1);
}

private static long mergeSortAndCount(int[] array, int left, int right) {


long count = 0;
if (left < right) {
int mid = (left + right) / 2;
count += mergeSortAndCount(array, left, mid);
count += mergeSortAndCount(array, mid + 1, right);
count += mergeAndCount(array, left, mid, right);
}
return count;
}

private static long mergeAndCount(int[] array, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;

int[] leftArray = new int[n1];


int[] rightArray = new int[n2];

for (int i = 0; i < n1; i++) {


leftArray[i] = array[left + i];
}
for (int j = 0; j < n2; j++) {
rightArray[j] = array[mid + 1 + j];
}

int i = 0, j = 0;
int k = left;
long count = 0;

while (i < n1 && j < n2) {


if (leftArray[i] <= rightArray[j]) {
array[k++] = leftArray[i++];
} else {
array[k++] = rightArray[j++];
count += (n1 - i); // Number of inversions
}
}

while (i < n1) {


array[k++] = leftArray[i++];
}

while (j < n2) {


array[k++] = rightArray[j++];
}

return count;
}

public static void main(String[] args) throws IOException {


BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new
OutputStreamWriter(System.out));

int n = Integer.parseInt(bufferedReader.readLine().trim());
int[] array = new int[n];
String[] arrayItems = bufferedReader.readLine().trim().split(" ");

for (int i = 0; i < n; i++) {


array[i] = Integer.parseInt(arrayItems[i]);
}

long result = countInversions(array);


bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();

bufferedReader.close();
bufferedWriter.close();
}
}
-------------------------------------

//sorting

import java.io.*;
import java.util.*;

public class Solution {

public static void main(String[] args) throws IOException {


BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(System.in));
String input = bufferedReader.readLine().trim();

// Convert input to linked list


ListNode head = parseInputToLinkedList(input);

// Sort the linked list


ListNode sortedHead = sortList(head);

// Convert sorted linked list to output format


String result = linkedListToString(sortedHead);

// Print the result


System.out.println(result);

bufferedReader.close();
}

// Convert a comma-separated string to a linked list


private static ListNode parseInputToLinkedList(String input) {
if (input.isEmpty()) return null;

String[] values = input.split(",");


ListNode head = new ListNode(Integer.parseInt(values[0]));
ListNode current = head;

for (int i = 1; i < values.length; i++) {


current.next = new ListNode(Integer.parseInt(values[i]));
current = current.next;
}

return head;
}

// Convert a linked list to a comma-separated string


private static String linkedListToString(ListNode head) {
if (head == null) return "";

StringBuilder sb = new StringBuilder();


ListNode current = head;

while (current != null) {


sb.append(current.val);
if (current.next != null) {
sb.append(",");
}
current = current.next;
}

return sb.toString();
}

// Function to sort the linked list


public static ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}

ListNode middle = getMiddle(head);


ListNode nextOfMiddle = middle.next;
middle.next = null;

ListNode left = sortList(head);


ListNode right = sortList(nextOfMiddle);

return merge(left, right);


}

// Function to find the middle of the linked list


private static ListNode getMiddle(ListNode head) {
if (head == null) return head;

ListNode slow = head;


ListNode fast = head;

while (fast.next != null && fast.next.next != null) {


slow = slow.next;
fast = fast.next.next;
}

return slow;
}

// Function to merge two sorted linked lists


private static ListNode merge(ListNode left, ListNode right) {
ListNode dummy = new ListNode(0);
ListNode current = dummy;

while (left != null && right != null) {


if (left.val <= right.val) {
current.next = left;
left = left.next;
} else {
current.next = right;
right = right.next;
}
current = current.next;
}

if (left != null) {
current.next = left;
}

if (right != null) {
current.next = right;
}

return dummy.next;
}
}

// Definition for singly-linked list.


class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}

Greedy

//Dijkistra
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;

class Result {

public static List<Integer> shortestReach(int n, List<List<Integer>> edges, int


s) {
// Create an adjacency list to represent the graph
List<List<int[]>> graph = new ArrayList<>(n + 1);
for (int i = 0; i <= n; i++) {
graph.add(new ArrayList<>());
}

// Fill the graph with edges


for (List<Integer> edge : edges) {
int u = edge.get(0);
int v = edge.get(1);
int w = edge.get(2);
graph.get(u).add(new int[]{v, w});
graph.get(v).add(new int[]{u, w}); // Undirected graph
}

// Dijkstra's algorithm to find the shortest path from node s


int[] distances = new int[n + 1];
Arrays.fill(distances, Integer.MAX_VALUE);
distances[s] = 0;

PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a ->


a[1]));
pq.offer(new int[]{s, 0}); // {node, distance}

while (!pq.isEmpty()) {
int[] current = pq.poll();
int currentNode = current[0];
int currentDistance = current[1];

// Explore neighbors
for (int[] neighbor : graph.get(currentNode)) {
int nextNode = neighbor[0];
int weight = neighbor[1];

// Calculate the new distance


if (currentDistance + weight < distances[nextNode]) {
distances[nextNode] = currentDistance + weight;
pq.offer(new int[]{nextNode, distances[nextNode]});
}
}
}
// Prepare the result, excluding the starting node
List<Integer> result = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (i != s) {
result.add(distances[i] == Integer.MAX_VALUE ? -1 : distances[i]);
}
}

return result;
}
}

public class Solution {


public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new
OutputStreamWriter(System.out));

int t = Integer.parseInt(bufferedReader.readLine().trim());

for (int tItr = 0; tItr < t; tItr++) {


String[] firstMultipleInput = bufferedReader.readLine().trim().split("
");
int n = Integer.parseInt(firstMultipleInput[0]);
int m = Integer.parseInt(firstMultipleInput[1]);

List<List<Integer>> edges = new ArrayList<>();

for (int i = 0; i < m; i++) {


edges.add(
Arrays.stream(bufferedReader.readLine().trim().split(" "))
.map(Integer::parseInt)
.collect(toList())
);
}

int s = Integer.parseInt(bufferedReader.readLine().trim());
List<Integer> result = Result.shortestReach(n, edges, s);

bufferedWriter.write(
result.stream()
.map(Object::toString)
.collect(Collectors.joining(" ")) + "\n"
);
}

bufferedReader.close();
bufferedWriter.close();
}
}

//

//Prim
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

/*
* Complete the 'prims' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. INTEGER n
* 2. 2D_INTEGER_ARRAY edges
* 3. INTEGER start
*/

public static int prims(int n, List<List<Integer>> edges, int start) {


// Create adjacency list
List<List<int[]>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) {
adj.add(new ArrayList<>());
}
for (List<Integer> edge : edges) {
int u = edge.get(0) - 1;
int v = edge.get(1) - 1;
int w = edge.get(2);
adj.get(u).add(new int[]{v, w});
adj.get(v).add(new int[]{u, w});
}

// Min-Heap to select the edge with the smallest weight


PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a ->
a[1]));
boolean[] inMST = new boolean[n];
int totalCost = 0;

// Start with the given start node


pq.add(new int[]{start - 1, 0});
while (!pq.isEmpty()) {
int[] current = pq.poll();
int u = current[0];
int weight = current[1];

if (inMST[u]) continue; // If already in MST, skip

inMST[u] = true; // Mark this node as included in MST


totalCost += weight;

// Add all adjacent edges to the priority queue


for (int[] neighbor : adj.get(u)) {
int v = neighbor[0];
int w = neighbor[1];
if (!inMST[v]) {
pq.add(new int[]{v, w});
}
}
}

// Check if all nodes are included in MST


for (boolean included : inMST) {
if (!included) return -1; // Not all nodes are connected
}

return totalCost;
}

public class Solution {


public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new
FileWriter(System.getenv("OUTPUT_PATH")));

String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\\s+$",


"").split(" ");

int n = Integer.parseInt(firstMultipleInput[0]);

int m = Integer.parseInt(firstMultipleInput[1]);
List<List<Integer>> edges = new ArrayList<>();

IntStream.range(0, m).forEach(i -> {


try {
edges.add(
Stream.of(bufferedReader.readLine().replaceAll("\\s+$",
"").split(" "))
.map(Integer::parseInt)
.collect(toList())
);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
});

int start = Integer.parseInt(bufferedReader.readLine().trim());

int result = Result.prims(n, edges, start);

bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();

bufferedReader.close();
bufferedWriter.close();
}
}

//Kruskal

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

class Result {

// Helper class for Union-Find


static class UnionFind {
private int[] parent;
private int[] rank;

UnionFind(int size) {
parent = new int[size];
rank = new int[size];
for (int i = 0; i < size; i++) {
parent[i] = i;
rank[i] = 0;
}
}

int find(int u) {
if (parent[u] != u) {
parent[u] = find(parent[u]); // Path compression
}
return parent[u];
}

void union(int u, int v) {


int rootU = find(u);
int rootV = find(v);

if (rootU != rootV) {
if (rank[rootU] > rank[rootV]) {
parent[rootV] = rootU;
} else if (rank[rootU] < rank[rootV]) {
parent[rootU] = rootV;
} else {
parent[rootV] = rootU;
rank[rootU]++;
}
}
}
}

public static int kruskals(int gNodes, List<Integer> gFrom, List<Integer> gTo,


List<Integer> gWeight) {
// Step 1: Prepare the edges
List<Edge> edges = new ArrayList<>();
for (int i = 0; i < gWeight.size(); i++) {
edges.add(new Edge(gFrom.get(i) - 1, gTo.get(i) - 1, gWeight.get(i)));
}

// Step 2: Sort the edges


edges.sort((e1, e2) -> {
if (e1.weight != e2.weight) return Integer.compare(e1.weight,
e2.weight);
int sum1 = e1.u + e1.v;
int sum2 = e2.u + e2.v;
return Integer.compare(sum1, sum2);
});

// Step 3: Kruskal's algorithm


UnionFind uf = new UnionFind(gNodes);
int totalWeight = 0;

for (Edge edge : edges) {


int u = edge.u;
int v = edge.v;
if (uf.find(u) != uf.find(v)) {
uf.union(u, v);
totalWeight += edge.weight;
}
}

return totalWeight;
}

// Edge class
static class Edge {
int u, v, weight;

Edge(int u, int v, int weight) {


this.u = u;
this.v = v;
this.weight = weight;
}
}
}

public class Solution {


public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new
FileWriter(System.getenv("OUTPUT_PATH")));

String[] gNodesEdges = bufferedReader.readLine().replaceAll("\\s+$",


"").split(" ");

int gNodes = Integer.parseInt(gNodesEdges[0]);


int gEdges = Integer.parseInt(gNodesEdges[1]);

List<Integer> gFrom = new ArrayList<>();


List<Integer> gTo = new ArrayList<>();
List<Integer> gWeight = new ArrayList<>();

IntStream.range(0, gEdges).forEach(i -> {


try {
String[] gFromToWeight = bufferedReader.readLine().replaceAll("\\s+
$", "").split(" ");
gFrom.add(Integer.parseInt(gFromToWeight[0]));
gTo.add(Integer.parseInt(gFromToWeight[1]));
gWeight.add(Integer.parseInt(gFromToWeight[2]));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
});

int result = Result.kruskals(gNodes, gFrom, gTo, gWeight);


bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();

bufferedReader.close();
bufferedWriter.close();
}
}

// Jim and the orders

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

/*
* Complete the 'jimOrders' function below.
*
* The function is expected to return an INTEGER_ARRAY.
* The function accepts 2D_INTEGER_ARRAY orders as parameter.
*/

public static List<Integer> jimOrders(List<List<Integer>> orders) {


// Write your code here

List<Integer>list=new ArrayList<>();
for(int i=0;i<orders.size();i++){
list.add(orders.get(i).get(0)+orders.get(i).get(1));
}
List<Integer>list2=new ArrayList<>(list);
Collections.sort(list2);// for sorting list
List<Integer>res=new ArrayList<>();
for(int i=0;i<list2.size();i++){
int a=list.indexOf(list2.get(i));
res.add(a+1);
list.set(a,123234);
}
return res;
}

public class Solution {


public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new
FileWriter(System.getenv("OUTPUT_PATH")));

int n = Integer.parseInt(bufferedReader.readLine().trim());

List<List<Integer>> orders = new ArrayList<>();

IntStream.range(0, n).forEach(i -> {


try {
orders.add(
Stream.of(bufferedReader.readLine().replaceAll("\\s+$",
"").split(" "))
.map(Integer::parseInt)
.collect(toList())
);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
});

List<Integer> result = Result.jimOrders(orders);

bufferedWriter.write(
result.stream()
.map(Object::toString)
.collect(joining(" "))
+ "\n"
);

bufferedReader.close();
bufferedWriter.close();
}
}

//Priyanka and the toys

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

/*
* Complete the 'toys' function below.
*
* The function is expected to return an INTEGER.
* The function accepts INTEGER_ARRAY w as parameter.
*/

public static int toys(List<Integer> w) {


// Write your code here
Collections.sort(w);

// Initialize count of groups


int groups = 0;
int i = 0;

while (i < w.size()) {


// Start a new group with the current toy
int groupStartWeight = w.get(i);
groups++;

// Move to the next toy that can be part of the current group
while (i < w.size() && w.get(i) <= groupStartWeight + 4) {
i++;
}
}

return groups;
}

public class Solution {


public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new
FileWriter(System.getenv("OUTPUT_PATH")));
int n = Integer.parseInt(bufferedReader.readLine().trim());

List<Integer> w = Stream.of(bufferedReader.readLine().replaceAll("\\s+$",
"").split(" "))
.map(Integer::parseInt)
.collect(toList());

int result = Result.toys(w);

bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();

bufferedReader.close();
bufferedWriter.close();
}
}

//Minimum sub-sequence in Non Increasing order

import java.util.*;
import java.util.stream.Collectors;
public class Solution {

public static List<Integer> findMinimumSubsequence(List<Integer> nums) {


// Step 1: Sort the array in non-increasing order
Collections.sort(nums, Collections.reverseOrder());

int totalSum = nums.stream().mapToInt(Integer::intValue).sum();


int subsequenceSum = 0;
List<Integer> subsequence = new ArrayList<>();

// Step 2: Select elements for the subsequence


for (int num : nums) {
subsequence.add(num);
subsequenceSum += num;
if (subsequenceSum > totalSum - subsequenceSum) {
break;
}
}

// The subsequence is already in non-increasing order


return subsequence;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Read the input


String[] input = scanner.nextLine().split(" ");
List<Integer> nums = new ArrayList<>();

for (String s : input) {


nums.add(Integer.parseInt(s));
}

// Find the minimum subsequence


List<Integer> result = findMinimumSubsequence(nums);

// Print the result

System.out.println(result.stream().map(String::valueOf).collect(Collectors.joining(
" ")));
}
}

//Task scheduler

import java.io.*;
import java.util.*;

public class Solution {

public static void main(String[] args) throws IOException {


// Reading input from STDIN
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
String[] tasks = reader.readLine().split(" ");
int n = Integer.parseInt(reader.readLine().trim());

// Calculate the result


int result = leastInterval(tasks, n);
System.out.println(result);
}

public static int leastInterval(String[] tasks, int n) {


// Frequency map to count occurrences of each task
Map<Character, Integer> frequencyMap = new HashMap<>();
for (String task : tasks) {
char taskChar = task.charAt(0);
frequencyMap.put(taskChar, frequencyMap.getOrDefault(taskChar, 0) + 1);
}
// Find the maximum frequency of any task
int maxFrequency = Collections.max(frequencyMap.values());

// Count how many tasks have the maximum frequency


int maxCount = 0;
for (int freq : frequencyMap.values()) {
if (freq == maxFrequency) {
maxCount++;
}
}

// Calculate the minimum number of units of time required


int totalParts = maxFrequency - 1;
int emptySlots = totalParts * (n + 1);
int availableSlots = emptySlots + maxCount;

return Math.max(availableSlots, tasks.length);


}
}

Dynamic programming

//The longest commom subsequence

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

class Result {
public static List<Integer> longestCommonSubsequence(List<Integer> a,
List<Integer> b) {
int n = a.size();
int m = b.size();

int[][] dp = new int[n+1][m+1];

// Build the DP table


for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (a.get(i-1).equals(b.get(j-1))) {
dp[i][j] = dp[i-1][j-1] + 1;
} else {
dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
}
}
}

// Reconstruct the LCS


List<Integer> lcs = new ArrayList<>();
int i = n;
int j = m;
while (i > 0 && j > 0) {
if (a.get(i-1).equals(b.get(j-1))) {
lcs.add(a.get(i-1));
i--;
j--;
} else if (dp[i-1][j] >= dp[i][j-1]) {
i--;
} else {
j--;
}
}

Collections.reverse(lcs);
return lcs;
}
}

public class Solution {


public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new
OutputStreamWriter(System.out));

String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\\s+$",


"").split(" ");
int n = Integer.parseInt(firstMultipleInput[0]);
int m = Integer.parseInt(firstMultipleInput[1]);

List<Integer> a = Arrays.stream(bufferedReader.readLine().replaceAll("\\s+
$", "").split(" "))
.map(Integer::parseInt)
.collect(Collectors.toList());

List<Integer> b = Arrays.stream(bufferedReader.readLine().replaceAll("\\s+
$", "").split(" "))
.map(Integer::parseInt)
.collect(Collectors.toList());

List<Integer> result = Result.longestCommonSubsequence(a, b);

bufferedWriter.write(result.stream().map(Object::toString).collect(Collectors.joini
ng(" ")) + "\n");

bufferedReader.close();
bufferedWriter.close();
}
}

//Coin change problem


import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

/*
* Complete the 'getWays' function below.
*
* The function is expected to return a LONG_INTEGER.
* The function accepts following parameters:
* 1. INTEGER n
* 2. LONG_INTEGER_ARRAY c
*/
public static long getWays(int n, List<Long> c) {
// Create a DP array to store the number of ways to make each amount
long[] dp = new long[n + 1];
dp[0] = 1; // There is 1 way to make change for 0 amount (using no coins)

// Update the DP table based on each coin denomination


for (long coin : c) {
for (int amount = (int) coin; amount <= n; amount++) {
dp[amount] += dp[amount - (int) coin];
}
}

return dp[n];
}

public class Solution {


public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new
FileWriter(System.getenv("OUTPUT_PATH")));

String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\\s+$",


"").split(" ");

int n = Integer.parseInt(firstMultipleInput[0]);
int m = Integer.parseInt(firstMultipleInput[1]);

List<Long> c = Stream.of(bufferedReader.readLine().replaceAll("\\s+$",
"").split(" "))
.map(Long::parseLong)
.collect(toList());

// Print the number of ways of making change for 'n' units using coins
having the values given by 'c'

long ways = Result.getWays(n, c);

bufferedWriter.write(String.valueOf(ways));
bufferedWriter.newLine();

bufferedReader.close();
bufferedWriter.close();
}
}

// Longest increasing subsequence

import java.io.*;
import java.util.*;

public class CodeSprintJuly16qB {

static final int mod = (int)1e9 + 7;


static long f[], inv[];

public static void main(String[] args) {


InputReader in = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);

int t = in.nextInt();

f = new long[1001000];
f[0] = 1;
for (int i = 1; i < f.length; i++)
f[i] = (i * f[i - 1]) % mod;

inv = new long[f.length];


inv[inv.length - 1] = pow(f[inv.length - 1], mod - 2);
for (int i = inv.length - 2; i >= 0; i--)
inv[i] = (inv[i + 1] * (i + 1)) % mod;

while (t-- > 0) {


int m = in.nextInt();
int n = in.nextInt();
long ans = 0;
long A = pow(n - 1, 0);
long B = pow(n, m - n);
long invN = pow(n, mod - 2);
for (int last = n; last <= m; last++) {
long now = C(last - 1, n - 1);
now *= A;
now %= mod;
now *= B;
now %= mod;
ans += now;
A *= n - 1;
A %= mod;
B *= invN;
B %= mod;
}
w.println(ans % mod);
}
w.close();
}

static long C(int n, int r) {


long ans = f[n];
ans *= inv[r];
ans %= mod;
ans *= inv[n - r];
ans %= mod;
return ans;
}

static long pow(long a, int b) {


if (b == 0)
return 1;
long t = pow(a, b >> 1);
t = (t * t) % mod;
if ( (b & 1) == 1)
t = (t * a) % mod;
return t;
}

static class InputReader {

private final InputStream stream;


private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;

public InputReader(InputStream stream) {


this.stream = stream;
}

public int snext() {


if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}

public int nextInt() {


int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}

public long nextLong() {


int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}

public String readString() {


int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}

public boolean isSpaceChar(int c) {


if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}

public interface SpaceCharFilter {


public boolean isSpaceChar(int ch);
}
}
}

//Knapsack

import java.io.*;
import java.util.*;
import java.util.stream.*;

class Result {

/*
* Complete the 'unboundedKnapsack' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. INTEGER k
* 2. INTEGER_ARRAY arr
*/

public static int unboundedKnapsack(int k, List<Integer> arr) {


int[] dp = new int[k + 1];

// Initialize the dp array


Arrays.fill(dp, 0);

// Fill the dp array


for (int i = 1; i <= k; i++) {
for (int weight : arr) {
if (weight <= i) {
dp[i] = Math.max(dp[i], dp[i - weight] + weight);
}
}
}

return dp[k];
}
}

public class Solution {


public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new
OutputStreamWriter(System.out));

int t = Integer.parseInt(bufferedReader.readLine().trim());

while (t-- > 0) {


String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\\
s+$", "").split(" ");
int n = Integer.parseInt(firstMultipleInput[0]);
int k = Integer.parseInt(firstMultipleInput[1]);

List<Integer> arr = Stream.of(bufferedReader.readLine().replaceAll("\\


s+$", "").split(" "))
.map(Integer::parseInt)
.collect(Collectors.toList());

int result = Result.unboundedKnapsack(k, arr);

bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
}

bufferedReader.close();
bufferedWriter.close();
}
}
//Maximum subarray

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

/*
* Complete the 'maxSubarray' function below.
*
* The function is expected to return an INTEGER_ARRAY.
* The function accepts INTEGER_ARRAY arr as parameter.
*/

public static List<Integer> maxSubarray(List<Integer> arr) {


int maxContiguous = Integer.MIN_VALUE;
int currentMax = 0;
int maxNonContiguous = Integer.MIN_VALUE;
int sumNonContiguous = 0;
boolean hasPositive = false;

for (int num : arr) {


currentMax = Math.max(num, currentMax + num);
maxContiguous = Math.max(maxContiguous, currentMax);

if (num > 0) {
sumNonContiguous += num;
hasPositive = true;
} else {
maxNonContiguous = Math.max(maxNonContiguous, num);
}
}

if (!hasPositive) {
sumNonContiguous = maxNonContiguous;
}

return Arrays.asList(maxContiguous, sumNonContiguous);


}

}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new
FileWriter(System.getenv("OUTPUT_PATH")));

int t = Integer.parseInt(bufferedReader.readLine().trim());

IntStream.range(0, t).forEach(tItr -> {


try {
int n = Integer.parseInt(bufferedReader.readLine().trim());

List<Integer> arr =
Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Integer::parseInt)
.collect(toList());

List<Integer> result = Result.maxSubarray(arr);

bufferedWriter.write(
result.stream()
.map(Object::toString)
.collect(joining(" "))
+ "\n"
);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
});

bufferedReader.close();
bufferedWriter.close();
}
}

// find the path

Site iconTheCScience
HackerRank Find the Path Problem Solution
Yashwant Parihar Yashwant Parihar
1 year ago
In this post, we well solve HackerRank Find the Path Problem Solution.
You are given a table, a. with n rows and m columns. The top-left corner of the
table has coordinates (0, 0), and the bottom-right corner has coordinates (n-1, m-
1). The th cell contains integer aj.
A path in the table is a sequence of cells (r1, 1), (r2, C2),…, (rk, Ck) such that
for each {1,…,k-1}, cell (r, c) and cell (ri+1, C++1) share a side.
The weight of the path (r₁, c₁), (r₂, C2),…, (rk, Ck) is defined by 1 ar,,&, where
arc is the weight of the cell (r, c).
You must answer q queries. In each query, you are given the coordinates of two
cells, (ri, ci) and (r2, C2). You must find and print the minimum possible weight
of a path connecting them.
Note: A cell can share sides with at most 4 other cells. A cell with coordinates
(r, c) shares sides with (r-1,c), (r+1,c), (r, c-1) and (r, c + 1).

Input Format
The first line contains 2 space-separated integers, n (the number of rows in a) and
m (the number of columns in a), respectively.
Each of n subsequent lines contains m space-separated integers. The th integer in
the ¿th
line denotes the value of aij.
The next line contains a single integer, q, denoting the number of queries.
Each of the q subsequent lines describes a query in the form of 4 space-separated
integers:

C1, r2, and c₂, respectively.


Sample Input

3 5
0 0 0 0 0
1 9 9 9 1
0 0 0 0 0
3
0 0 2 4
0 3 2 3
1 1 1 3
Sample Output

1
1
18

HackerRank Find the Path Problem Solution


HackerRank Find the Path Problem Solution
Table of Contents

Find the Path C Solution


Find the Path C++ Solution
Find the Path C Sharp Solution
Find the Path Java Solution
Find the Path JavaScript Solution
Find the Path Python Solution
Find the Path C Solution
#include <stdio.h>
#include <stdlib.h>
#define INF 1000000000
typedef struct{
int i;
int j;
int w;
} node;
int min(int x,int y);
void build(int v,int l,int r);
void solve(int v,int l,int r);
void DJ(int si,int sj,int l,int r,int **d);
void heap_insert(node *elem,int *size);
void heap_update(node *elem);
void heap_read(int *size,node *ans);
int n,r1,c1,r2,c2,ans,a[7][5000],heap_list[7][5000],****d;
node heap[40000];

int main(){
int m,q,i,j;
scanf("%d%d",&n,&m);
d=(int****)malloc(m*4*sizeof(int***));
for(i=0;i<n;i++)
for(j=0;j<m;j++)
scanf("%d",&a[i][j]);
build(1,0,m-1);
scanf("%d",&q);
while(q--){
scanf("%d%d%d%d",&r1,&c1,&r2,&c2);
ans=INF;
solve(1,0,m-1);
printf("%d\n",ans);
}
return 0;
}
int min(int x,int y){
return (x<y)?x:y;
}
void build(int v,int l,int r){
int tm,i,j;
tm=(l+r)/2;
d[v]=(int***)malloc(n*sizeof(int**));
for(i=0;i<n;i++){
d[v][i]=(int**)malloc(n*sizeof(int*));
for(j=0;j<n;j++)
d[v][i][j]=(int*)malloc((r-l+1)*sizeof(int));
DJ(i,tm-l,l,r,d[v][i]);
}
if(l!=r){
build(2*v,l,tm);
build(2*v+1,tm+1,r);
}
return;
}
void solve(int v,int l,int r){
int tm,i;
tm=(l+r)/2;
for(i=0;i<n;i++)
ans=min(ans,d[v][i][r1][c1-l]+d[v][i][r2][c2-l]+a[i][tm]);
if(c1<tm && c2<tm)
solve(2*v,l,tm);
else if(c1>tm && c2>tm)
solve(2*v+1,tm+1,r);
return;
}
void DJ(int si,int sj,int l,int r,int **d){
int i,j,next_solve_i,next_solve_j,heap_size=0;
node elem;
for(i=0;i<n;i++)
for(j=0;j<r-l+1;j++)
d[i][j]=-1;
d[si][sj]=0;
next_solve_i=si;
next_solve_j=sj;
while(1){
if(next_solve_i){
if(d[next_solve_i-1][next_solve_j]==-1 || d[next_solve_i-1]
[next_solve_j]>d[next_solve_i][next_solve_j]+a[next_solve_i-1][next_solve_j+l]){
elem.i=next_solve_i-1;
elem.j=next_solve_j;
elem.w=d[next_solve_i][next_solve_j]+a[next_solve_i-1][next_solve_j+l];
if(d[next_solve_i-1][next_solve_j]==-1)
heap_insert(&elem,&heap_size);
else
heap_update(&elem);
d[next_solve_i-1][next_solve_j]=d[next_solve_i][next_solve_j]
+a[next_solve_i-1][next_solve_j+l];
}
}
if(next_solve_i+1<n){
if(d[next_solve_i+1][next_solve_j]==-1 || d[next_solve_i+1]
[next_solve_j]>d[next_solve_i][next_solve_j]+a[next_solve_i+1][next_solve_j+l]){
elem.i=next_solve_i+1;
elem.j=next_solve_j;
elem.w=d[next_solve_i][next_solve_j]+a[next_solve_i+1][next_solve_j+l];
if(d[next_solve_i+1][next_solve_j]==-1)
heap_insert(&elem,&heap_size);
else
heap_update(&elem);
d[next_solve_i+1][next_solve_j]=d[next_solve_i][next_solve_j]
+a[next_solve_i+1][next_solve_j+l];
}
}
if(next_solve_j){
if(d[next_solve_i][next_solve_j-1]==-1 || d[next_solve_i][next_solve_j-
1]>d[next_solve_i][next_solve_j]+a[next_solve_i][next_solve_j-1+l]){
elem.i=next_solve_i;
elem.j=next_solve_j-1;
elem.w=d[next_solve_i][next_solve_j]+a[next_solve_i][next_solve_j-1+l];
if(d[next_solve_i][next_solve_j-1]==-1)
heap_insert(&elem,&heap_size);
else
heap_update(&elem);
d[next_solve_i][next_solve_j-1]=d[next_solve_i][next_solve_j]
+a[next_solve_i][next_solve_j-1+l];
}
}
if(next_solve_j+1+l<=r){
if(d[next_solve_i][next_solve_j+1]==-1 || d[next_solve_i]
[next_solve_j+1]>d[next_solve_i][next_solve_j]+a[next_solve_i][next_solve_j+1+l]){
elem.i=next_solve_i;
elem.j=next_solve_j+1;
elem.w=d[next_solve_i][next_solve_j]+a[next_solve_i][next_solve_j+1+l];
if(d[next_solve_i][next_solve_j+1]==-1)
heap_insert(&elem,&heap_size);
else
heap_update(&elem);
d[next_solve_i][next_solve_j+1]=d[next_solve_i][next_solve_j]
+a[next_solve_i][next_solve_j+1+l];
}
}
if(heap_size==0)
break;
heap_read(&heap_size,&elem);
next_solve_i=elem.i;
next_solve_j=elem.j;
}
return;
}
void heap_insert(node *elem,int *size){
(*size)++;
int index=(*size);
while(index>1 && elem->w<heap[index/2].w){
heap[index]=heap[index/2];
heap_list[heap[index].i][heap[index].j]=index;
index/=2;
}
heap[index]=(*elem);
heap_list[elem->i][elem->j]=index;
return;
}
void heap_update(node *elem){
int index=heap_list[elem->i][elem->j];
while(index>1 && elem->w<heap[index/2].w){
heap[index]=heap[index/2];
heap_list[heap[index].i][heap[index].j]=index;
index/=2;
}
heap[index]=(*elem);
heap_list[elem->i][elem->j]=index;
return;
}
void heap_read(int *size,node *ans){
(*ans)=heap[1];
int index=1;
while(index*2<*size && heap[*size].w>heap[index*2].w || index*2+1<*size &&
heap[*size].w>heap[index*2+1].w){
index=(heap[index*2].w>heap[index*2+1].w)?index*2+1:index*2;
heap[index/2]=heap[index];
heap_list[heap[index].i][heap[index].j]=index/2;
}
heap[index]=heap[*size];
heap_list[heap[index].i][heap[index].j]=index;
(*size)--;
return;
}
Find the Path C++ Solution
#include <bits/stdc++.h>

using namespace std;

int N, M;
vector<vector<int64_t>> G;
const int64_t INF = 1e11;

vector<vector<int64_t>> dijk(int r, int c, int L, int R) {


set<pair<int64_t, pair<int, int>>> Q;
vector<vector<int64_t>> D(N, vector<int64_t>(R-L+1, INF));
Q.insert(make_pair(0, make_pair(r,c)));
vector<vector<int>> dirs = {{1,0},{0,1},{-1,0},{0,-1}};
while (!Q.empty()) {
auto curr = *Q.begin();
Q.erase(Q.begin());
int64_t d = curr.first;
int r = curr.second.first, c = curr.second.second;
if (d > D[r][c-L]) {
continue;
}
D[r][c-L] = d;
for (auto dir : dirs) {
int cr = r+dir[0];
int cc = c+dir[1];
if (cr < 0 || cc < L || cr >= N || cc > R)
continue;
int64_t cd = d + G[cr][cc];
if (cd < D[cr][cc-L]) {
Q.insert(make_pair(cd, make_pair(cr, cc)));
D[cr][cc-L] = cd;
}
}
}
return D;
}

vector<vector<int>> Qs;
vector<int64_t> ans;

vector<unordered_map<int, pair<int, vector<vector<int64_t>>>>> SPs(7);

void div_and_conq(int l, int r, vector<int> Qis) {


if (l > r)
return;
int mid = (r+l)/2;
for (int i = 0; i < N; ++i) {
SPs[i][mid] = make_pair(l, dijk(i, mid, l, r));
}
vector<int> Qls, Qrs;
for (int i : Qis) {
if (Qs[i][1] < mid && Qs[i][3] < mid) {
Qls.push_back(i);
} else if (Qs[i][1] > mid && Qs[i][3] > mid) {
Qrs.push_back(i);
} else {
for (int j = 0; j < N; ++j) {
for (auto& kv : SPs[j]) {
int mid = kv.first;
int upperl = kv.second.first;
auto& SP = kv.second.second;
int64_t d = SP[Qs[i][0]][Qs[i][1]-upperl]+SP[Qs[i][2]][Qs[i]
[3]-upperl]+G[j][mid];
ans[i] = min(ans[i], d);
}
}
}
}
div_and_conq(l, mid-1, Qls);
div_and_conq(mid+1, r, Qrs);
for (int i = 0; i < N; ++i) {
SPs[i].erase(mid);
}
}

int main() {
ios::sync_with_stdio(false);
cin >> N >> M;
G.assign(N, vector<int64_t>(M));
for (auto &v : G) {
for (int64_t& i : v) {
cin >> i;
}
}
int Q;
cin >> Q;
Qs.resize(Q);
ans.assign(Q, INF);
vector<int> Qis;
for (int i = 0; i < Q; ++i) {
int a,b,c,d;
cin >> a >> b >> c >> d;
Qs[i] = {a,b,c,d};
Qis.push_back(i);
}
div_and_conq(0, M-1, Qis);
for (int64_t i : ans) {
cout << i << endl;
}
return 0;
}
Find the Path C Sharp Solution
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;

struct Node
{
public int w;
public int r;
public int c;

public Node(int w, int r, int c){


this.w = w;
this.r = r;
this.c = c;
}
}

class Heap
{
public int length = 0;
private Node[] heap;

public Heap(int n, int m){


this.heap = new Node[(int)(n*m*0.67)];
}

public void initialize(){


this.length = 0;
}

public void push (Node node){


this.heap[this.length] = node;
this.length++;
int node_w=node.w, node_i=this.length-1, parent_i;
while (node_i>0){
parent_i = (node_i-1)/2;
if (node_w>=this.heap[parent_i].w){
break;
}
else{
this.heap[node_i] = this.heap[parent_i];
this.heap[parent_i] = node;
node_i = parent_i;
}
}
}

public Node pop(){


Node node=this.heap[this.length-1], node_return=this.heap[0];
this.heap[0] = node;
this.length--;
int node_w=node.w, node_i=0,
child_l_i=node_i*2+1, child_r_i=child_l_i+1, child_s_i;
while (child_l_i<this.length){
if (child_r_i<this.length){
if (this.heap[child_r_i].w<this.heap[child_l_i].w){
child_s_i = child_r_i;
}
else{
child_s_i = child_l_i;
}
}
else{
child_s_i = child_l_i;
}
if (node_w<this.heap[child_s_i].w){
break;
}
else{
this.heap[node_i] = this.heap[child_s_i];
this.heap[child_s_i] = node;
node_i = child_s_i;
child_l_i = node_i*2+1;
child_r_i = child_l_i+1;
}
}
return node_return;
}
}

class Collectively
{
private int n, m, max_w;
private int [] middle_w;
private int [,,] map;
private List<List<int>> a;
private Heap heap;

public Collectively(List<List<int>> a, int n, int m, int max_w){


this.a = a;
this.n = n;
this.m = m;
this.max_w = max_w;
this.middle_w = new int[this.n];
this.map = new int[this.n, this.n, this.m];
this.heap = new Heap(n, m);
}

public float update_map(int left, int middle, int right){


int to_fill=(right-left+1)*this.n, filled=1, filled_all=1, w, r, r_, c, c_;
bool[,] explored;
Node node;
for (int i_n=0; i_n<this.n; i_n++){
this.middle_w[i_n] = this.a[i_n][middle];
explored = new bool[this.n, this.m];
heap.initialize();
heap.push(new Node(this.a[i_n][middle], i_n, middle));
explored[i_n, middle] = true;
this.map[i_n, i_n, middle] = this.a[i_n][middle];
filled = 1;
filled_all = 1;
while (true){
node = heap.pop();
if (filled>=to_fill){
break;
}
w = node.w;
c = node.c;
r = node.r;
c_ = c;
if (r>0){
r_ = r-1;
if (!explored[r_, c_]){
heap.push(new Node(this.a[r_][c_]+w, r_, c_));
explored[r_, c_] = true;
this.map[i_n, r_, c_] = this.a[r_][c_]+w;
filled_all += 1;
if (c_>=left && c_<=right){
filled++;
}
}
}
if (r<this.n-1){
r_ = r+1;
if (!explored[r_, c_]){
heap.push(new Node(this.a[r_][c_]+w, r_, c_));
explored[r_, c_] = true;
this.map[i_n, r_, c_] = this.a[r_][c_]+w;
filled_all += 1;
if (c_>=left && c_<=right){
filled++;
}
}
}
r_ = r;
if (c>0){
c_ = c-1;
if (!explored[r_, c_]){
heap.push(new Node(this.a[r_][c_]+w, r_, c_));
explored[r_, c_] = true;
this.map[i_n, r_, c_] = this.a[r_][c_]+w;
filled_all += 1;
if (c_>=left && c_<=right){
filled++;
}
}
}
if (c<this.m-1){
c_ = c+1;
if (!explored[r_, c_]){
heap.push(new Node(this.a[r_][c_]+w, r_, c_));
explored[r_, c_] = true;
this.map[i_n, r_, c_] = this.a[r_][c_]+w;
filled_all += 1;
if (c_>=left && c_<=right){
filled++;
}
}
}
}
}
return (float)(filled_all) / (float)(filled);
}

public int get_min_w(List<int> query){


int min_w = this.max_w, w;
for (int i_n=0; i_n<this.n; i_n++){
w = this.map[i_n, query[0], query[1]] +
this.map[i_n, query[2], query[3]] -
this.middle_w[i_n];
if (w<min_w){
min_w = w;
}
}
return min_w;
}
}

class Individually
{
private int n, m;
private List<List<int>> a;
private Heap heap;

public Individually(List<List<int>> a, int n, int m){


this.a = a;
this.n = n;
this.m = m;
this.heap = new Heap(n, m);
}

public int get_min_w(List<int> query){


int w, distance, r, r_, c, c_,
r_1 = query[0], c_1 = query[1], r_2 = query[2], c_2 = query[3];
bool[,] explored = new bool[this.n, this.m];
Node node;
heap.initialize();
explored[r_1, c_1] = true;
heap.push(new Node(this.a[r_1][c_1], r_1, c_1));
while (true){
node = heap.pop();
w = node.w;
c = node.c;
r = node.r;
distance = Math.Abs(r-r_2)+Math.Abs(c-c_2);
if (distance<=1){
if (distance==1){
return w+a[r_2][c_2];
}
else{
return w;
}
}
c_ = c;
if (r>0){
r_ = r-1;
if (!explored[r_, c_]){
heap.push(new Node(a[r_][c_]+w, r_, c_));
explored[r_, c_] = true;
}
}
if (r<n-1){
r_ = r+1;
if (!explored[r_, c_]){
heap.push(new Node(a[r_][c_]+w, r_, c_));
explored[r_, c_] = true;
}
}
r_ = r;
if (c>0){
c_ = c-1;
if (!explored[r_, c_]){
heap.push(new Node(a[r_][c_]+w, r_, c_));
explored[r_, c_] = true;
}
}
if (c<m-1){
c_ = c+1;
if (!explored[r_, c_]){
heap.push(new Node(a[r_][c_]+w, r_, c_));
explored[r_, c_] = true;
}
}
}
}
}

class WorkSpace
{
private int n, m;
public int[] result;
private List<List<int>> a, queries, index_remained;
private bool[] index_solved;
private Collectively collectively;
private Individually individually;

public WorkSpace(List<List<int>> a, List<List<int>> queries){


this.n = a.Count();
this.m = a[0].Count();
this.result = new int[queries.Count()];
this.a = a;
this.queries = queries;
// this.index_remained = new List<List<int>>();
this.index_solved = new bool[queries.Count()];
this.collectively = new Collectively(a, n, m, 3000*n*m+1);
this.individually = null;
}

public void solve(List<int> index_to_solve, int left, int right){


int middle = (int)((left + right) / 2);
List<int> index_solving = new List<int>();
List<int> index_unsolved_left = new List<int>();
List<int> index_unsolved_right = new List<int>();
foreach (int index in index_to_solve){
int dc_1 = this.queries[index][1] - middle,
dc_2 = this.queries[index][3] - middle;
if (dc_1*dc_2<=0){
index_solving.Add(index);
}
else if (dc_1<0){
index_unsolved_left.Add(index);
}
else if (dc_1>0){
index_unsolved_right.Add(index);
}
}
if (index_solving.Count()>this.n){
float ratio = this.collectively.update_map(left, middle, right);
foreach (int index in index_solving){
this.result[index] =
this.collectively.get_min_w(this.queries[index]);
this.index_solved[index] = true;
}
if (ratio<6.0){
this.solve(index_unsolved_left, left, middle-1);
this.solve(index_unsolved_right, middle+1, right);
}
}
}

public void solve_remained(){


this.collectively = null;
this.individually = new Individually(a, n, m);
for (int index=0; index<this.index_solved.Count(); index++){
if (!index_solved[index]){
this.result[index] =
this.individually.get_min_w(this.queries[index]);
}
}
}
}

class Result
{
public static List<int> shortestPath(List<List<int>> a, List<List<int>>
queries)
{
int m=a[0].Count();
WorkSpace work_space = new WorkSpace(a, queries);
work_space.solve(Enumerable.Range(0, queries.Count()).ToList(), 0, m-1);
work_space.solve_remained();
return new List<int>(work_space.result);
}
}

class Solution
{
public static void Main(string[] args)
{
TextWriter textWriter = new
StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
string[] firstMultipleInput = Console.ReadLine().TrimEnd().Split(' ');

int n = Convert.ToInt32(firstMultipleInput[0]);

int m = Convert.ToInt32(firstMultipleInput[1]);

List<List<int>> a = new List<List<int>>();

for (int i = 0; i < n; i++)


{
a.Add(Console.ReadLine().TrimEnd().Split(' ').ToList().Select(aTemp =>
Convert.ToInt32(aTemp)).ToList());
}

int q = Convert.ToInt32(Console.ReadLine().Trim());

List<List<int>> queries = new List<List<int>>();

for (int i = 0; i < q; i++)


{
queries.Add(Console.ReadLine().TrimEnd().Split('
').ToList().Select(queriesTemp => Convert.ToInt32(queriesTemp)).ToList());
}

List<int> result = Result.shortestPath(a, queries);

textWriter.WriteLine(String.Join("\n", result));

textWriter.Flush();
textWriter.Close();
}
}

Find the Path Java Solution


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;

public class C {
InputStream is;
PrintWriter out;
String INPUT = "";

void solve()
{
int n = ni(), m = ni();
int[][] a = new int[m][n];
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
a[j][i] = ni();
}
}
d = new long[m][n][][];

build(0, m, a);

int Q = ni();
for(int q = 0;q < Q;q++){
int sc = ni(), sr = ni();
int tc = ni(), tr = ni();
if(sr > tr){
{int du = tr; tr = sr; sr = du;}
{int du = tc; tc = sc; sc = du;}
}
out.println(go(0, m, sr, sc, tr, tc, a));
}

static long go(int L, int R, int sr, int sc, int tr, int tc, int[][] a)
{
int M = L+R>>>1;
int m = a[0].length;
long ret = Long.MAX_VALUE;
for(int i = 0;i < m;i++){
ret = Math.min(ret, d[M][i][sr-L][sc] + d[M][i][tr-L][tc] - a[M][i]);
}
if(sr <= M && M <= tr){
return ret;
}
if(R-L <= 1)return ret;
if(tr < M){
return Math.min(ret, go(L, M, sr, sc, tr, tc, a));
}else{
return Math.min(ret, go(M, R, sr, sc, tr, tc, a));
}
}

static long[][][][] d;

static void build(int L, int R, int[][] a)


{
int m = a[0].length;
int M = L+R>>>1;
if(d[M][0] != null)return;
for(int i = 0;i < m;i++){
d[M][i] = dijk(a, M, i, L, R);
}
if(R-L <= 1)return;
build(L, M, a);
build(M, R, a);
}

public static long[][] dijk(int[][] a, int sr, int sc, int L, int R)
{
int m = a[0].length;
long[][] td = new long[R-L][m];
for(int i = 0;i < R-L;i++){
Arrays.fill(td[i], Long.MAX_VALUE / 3);
}
td[sr-L][sc] = 0;
MinHeapL q = new MinHeapL((R-L)*m);
q.add((sr-L)*m+sc, 0L);
td[sr-L][sc] = a[sr][sc];

int[] dr = { 1, 0, -1, 0 };
int[] dc = { 0, 1, 0, -1 };

while(q.size() > 0){


int cur = q.argmin();
q.remove(cur);

int r = cur / m, c = cur % m;


for(int k = 0;k < 4;k++){
int nr = r + dr[k], nc = c + dc[k];
if(nr >= L-L && nr < R-L && nc >= 0 && nc < m){
long nd = td[r][c] + a[nr+L][nc];
if(nd < td[nr][nc]){
td[nr][nc] = nd;
q.update(nr*m+nc, nd);
}
}
}
}

return td;
}

public static class MinHeapL {


public long[] a;
public int[] map;
public int[] imap;
public int n;
public int pos;
public static long INF = Long.MAX_VALUE;

public MinHeapL(int m)
{
n = Integer.highestOneBit((m+1)<<1);
a = new long[n];
map = new int[n];
imap = new int[n];
Arrays.fill(a, INF);
Arrays.fill(map, -1);
Arrays.fill(imap, -1);
pos = 1;
}

public long add(int ind, long x)


{
int ret = imap[ind];
if(imap[ind] < 0){
a[pos] = x; map[pos] = ind; imap[ind] = pos;
pos++;
up(pos-1);
}
return ret != -1 ? a[ret] : x;
}

public long update(int ind, long x)


{
int ret = imap[ind];
if(imap[ind] < 0){
a[pos] = x; map[pos] = ind; imap[ind] = pos;
pos++;
up(pos-1);
}else{
a[ret] = x;
up(ret);
down(ret);
}
return x;
}

public long remove(int ind)


{
if(pos == 1)return INF;
if(imap[ind] == -1)return INF;

pos--;
int rem = imap[ind];
long ret = a[rem];
map[rem] = map[pos];
imap[map[pos]] = rem;
imap[ind] = -1;
a[rem] = a[pos];
a[pos] = INF;
map[pos] = -1;

up(rem);
down(rem);
return ret;
}

public long min() { return a[1]; }


public int argmin() { return map[1]; }
public int size() { return pos-1; }

private void up(int cur)


{
for(int c = cur, p = c>>>1;p >= 1 && a[p] > a[c];c>>>=1, p>>>=1){
long d = a[p]; a[p] = a[c]; a[c] = d;
int e = imap[map[p]]; imap[map[p]] = imap[map[c]]; imap[map[c]] =
e;
e = map[p]; map[p] = map[c]; map[c] = e;
}
}

private void down(int cur)


{
for(int c = cur;2*c < pos;){
int b = a[2*c] < a[2*c+1] ? 2*c : 2*c+1;
if(a[b] < a[c]){
long d = a[c]; a[c] = a[b]; a[b] = d;
int e = imap[map[c]]; imap[map[c]] = imap[map[b]]; imap[map[b]]
= e;
e = map[c]; map[c] = map[b]; map[b] = e;
c = b;
}else{
break;
}
}
}
}

void run() throws Exception


{
is = INPUT.isEmpty() ? System.in : new
ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);

long s = System.currentTimeMillis();
solve();
out.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}

public static void main(String[] args) throws Exception { new C().run(); }

private byte[] inbuf = new byte[1024];


private int lenbuf = 0, ptrbuf = 0;

private int readByte()


{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new
InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}

private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }


private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b));
return b; }

private double nd() { return Double.parseDouble(ns()); }


private char nc() { return (char)skip(); }

private String ns()


{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}

private char[][] nm(int n, int m)


{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}

private int[] na(int n)


{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}

private int ni()


{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}

while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}

private long nl()


{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}

while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}

private static void tr(Object... o)


{ System.out.println(Arrays.deepToString(o)); }
}

You might also like