stacks and queues i assess
Sat May 04 2024 04:20:35 GMT+0000 (Coordinated Universal Time)
Saved by @signup
//Hill.java
public class Hill {
public int findPairCount(int[] arr) {
int pairCount = 0;
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (canSeeEachOther(arr, i, j)) {
pairCount++;
}
}
}
return pairCount;
}
private boolean canSeeEachOther(int[] arr, int i, int j) {
for (int k = i + 1; k < j; k++) {
if (arr[k] >= arr[i] || arr[k] >= arr[j]) {
return false;
}
}
return true;
}
}
//Main.java
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Hill hill = new Hill();
int n = scanner.nextInt();
int[] heights = new int[n];
for (int i = 0; i < n; i++) {
heights[i] = scanner.nextInt();
}
int pairCount = hill.findPairCount(heights);
System.out.println( pairCount);
}
}
//2
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class Main {
static class Bug {
int power;
int position;
Bug(int power, int position) {
this.power = power;
this.position = position;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int X = scanner.nextInt();
Queue<Bug> queue = new LinkedList<>();
for (int i = 1; i <= N; i++) {
int power = scanner.nextInt();
queue.add(new Bug(power, i));
}
int[] selectedPositions = findSelectedPositions(N, X, queue);
for (int position : selectedPositions) {
System.out.print(position + " ");
}
}
static int[] findSelectedPositions(int N, int X, Queue<Bug> queue) {
int[] selectedPositions = new int[X];
for (int i = 0; i < X; i++) {
int maxPower = -1;
int maxIndex = -1;
Queue<Bug> tempQueue = new LinkedList<>();
for (int j = 0; j < X && !queue.isEmpty(); j++) {
Bug bug = queue.poll();
tempQueue.add(bug);
if (bug.power > maxPower) {
maxPower = bug.power;
maxIndex = bug.position;
}
}
selectedPositions[i] = maxIndex;
while (!tempQueue.isEmpty()) {
Bug bug = tempQueue.poll();
if (bug.position != maxIndex) {
if (bug.power > 0) {
bug.power--;
}
queue.add(bug);
}
}
}
return selectedPositions;
}
}



Comments