Problem 2
Mr. Seth is upset because of his short height. Now, he wants to imagine himself taller. So he decided to stand in
front of K pillars of different heights i.e. the je pillar has height h. Now to feel taller, he wanted to know how
many buildings he is able to see within the range [] both inclusive?
Input
.
The first line contains an integer K denoting the number of pillars.
The next line contains K integers denoting the height of je pillar
The next line contains a single integer Q (no. of queries).
Next, Q lines contain pairs I and r respectively.
Output
For every Q queries print the number of buildings visible in the range [1,1].
Constraints
.
1<=K, Q<=10
1<=}<=rc=K
1<=h<=10
Sample Input
Sample Output
5 2 3 7 9 8 11
4
06
15
26
Time Limit: 1
Memory Limit: 256
Source Limit
Explanation
In query 1-5, 7, 9, 11 pillars are visible so the answer is 4.
In query 2-2, 3, 7, 9 are visible so the answer is 4.
Answers
Answer:
sorry I didn't know these answer
Answer:
import java.util.*;
import java.io.*;
public class Feel_Taller{
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
StringBuilder sb = new StringBuilder();
int k = Integer.parseInt(br.readLine().trim());
StringTokenizer st = new StringTokenizer(br.readLine().trim());
long a[] = new long[k];
for(int i=0;i<k;i++)
a[i] = Long.parseLong(st.nextToken());
Stack<Integer> s = new Stack<Integer>();
int n = 0; //Number of elements in the stack
int p[] = new int[k] ;
for(int i = k-1;i>=0;i--)
{
while(!s.empty() && a[s.peek()]<=a[i]){
s.pop();
n--;
}
p[i] = n;
s.push(i);
n++;
}
//Queries
int q = Integer.parseInt(br.readLine().trim());
while(q-->0){
st = new StringTokenizer(br.readLine().trim());
int l = Integer.parseInt(st.nextToken());
int r = Integer.parseInt(st.nextToken());
if(r>=k)
r = k-1;
sb.append(p[l]-p[r]+1).append("\n");
}
pw.print(sb);
pw.flush();
pw.close();
}
}
#SPJ2