Can you reach A certain mountain range has N N mo...
बनाया गया: 26 मार्च 2025
बनाया गया: 26 मार्च 2025
1
∣H
i
−H
i−1
∣=1 for every
i
i.
On each mountain peak lives a single person.
A person can move from one mountain peak to an adjacent mountain peak (i.e. a person standing on the
i
i-th peak can move to
i
−
1
i−1 or
i
+
1
i+1).
However, they will refuse to move to a mountain that's of the same height as one that has been visited before.
For example, if the heights are
[
1
,
2
,
3
,
2
,
3
]
[1,2,3,2,3], the person who is initially on the first peak can move to the second and third peaks, but will not move to the fourth (since it has a height of
2
2, which has already been visited along the way).
Similarly, the person initially on the fourth peak can move to the third or the fifth peak, but will not move to the second peak, since it has a height of
2
2 which is the same as the starting height.
Two people are considered to have a friendship between them if they can both reach the same mountain via some sequence of moves.
In the above example of
[
1
,
2
,
3
,
2
,
3
]
[1,2,3,2,3], the people on mountains
2
2 and
3
3 are friends (person
2
2 can move to mountain
3
3), and the people on mountains
1
1 and
4
4 are also friends (they can both move to mountain
3
3). However, the people on mountains
1
1 and
5
5 are not friends, because there's no common mountain where they can meet.
Given the heights of the mountain peaks, find the number of friendships.
Input Format
The first line of input will contain a single integer
T
T, denoting the number of test cases.
Each test case consists of two lines of input.
The first line of each test case contains one integer
N
N — the number of mountain peaks.
The next line contains
N
N space-separated integers
H
1
,
H
2
,
…
,
H
N
H
1
,H
2
,…,H
N
, describing the mountain heights.
Output Format
For each test case, output on a new line a single integer: the number of friendships.
Constraints
1
≤
T
≤
1
0
5
1≤T≤10
5
1
≤
N
≤
2
⋅
1
0
5
1≤N≤2⋅10
5
1
∣H
i
−H
i−1
∣=1 for each
1
≤
i
<
N
1≤i<N
The sum of
N
N over all test cases won't exceed
2
⋅
1
0
5
2⋅10
5
.
Sample 1:
Input
Output
2
5
3 4 5 4 3
4
1 2 1 2
10
5
Explanation:
Test case
1
1: Every person is able to reach the highest mountain, i.e.
5
5. Since for every pair of people there's a mountain they can both reach, every pair of people will be friends.
Test case
2
2: The friendships are as follows:
Persons
1
1 and
2
2 are friends: they're already adjacent to each other so one of them can just move to the other.
Similarly
(
2
,
3
)
(2,3) and
(
3
,
4
)
(3,4) are friends.
Persons
1
1 and
3
3 are friends: they can both move to mountain
2
2 and meet there.
Similarly, persons
2
2 and
4
4 are friends, since they can meet at mountain
3
3.
However, there's no way for persons
1
1 and
4
4 to ever meet.
The total number of friendships is hence
5
5.
Did you like the problem statement?
More Info
Time limit1 secs
Memory limit1.5 GB
Source Limit50000 Bytes
import java.util.;
import java.lang.;
import java.io.*;
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
}
}
write a java solution
Analysis
We have an array of heights H[1..N]
with the property that adjacent heights differ by exactly 1, and a person starting on peak i can "walk" left or right along the chain but may never revisit a height that has been visited before on that walk. Two people (at positions i and j) are said to be friends if there is some peak k they can both reach (possibly via different walks).
A key (and somewhat tricky) insight is:
i and j are friends ⟺ there is some index k such that
• the contiguous subarray of indices [min(i,k) .. max(i,k)] has no repeated height (so i can reach k), and
• the contiguous subarray [min(j,k) .. max(j,k)] has no repeated height (so j can reach k).
Equivalently, one can show that:
It turns out one can count the number of friendly pairs by splitting into two main cases:
• Case B ("meet at or beyond j"):
If [i..j] has no repeated heights, then j ≤ bᵢ, where bᵢ is the largest index ≥ i such that [i..bᵢ] is distinct.
In other words, for each i, all j in the range (i..bᵢ] yield a friend‐pair (i,j).
• Case A ("meet strictly in the interior"):
If [i..j] does have repeats, it may still be possible to meet at some k with i < k < j.
One finds that the condition boils down to
cⱼ ≤ bᵢ < j
(plus i < j),
where cⱼ is the smallest index ≤ j for which [cⱼ..j] is distinct.
Intuitively, this means i's “forward‐distinct window” ends at bᵢ, which is still to the left of j (so [i..j] is not distinct).
But j can “go backward” at least one step (since cⱼ < j), and if cⱼ ≤ bᵢ, they can meet in between.
Hence, the counting strategy:
Compute for each i the value bᵢ = the furthest index ≥ i such that [i..bᵢ] is distinct.
Compute for each i the value cᵢ = the furthest index ≤ i such that [cᵢ..i] is distinct.
Let
• sumB = ∑(bᵢ−i) over all i, counting all pairs (i,j) with i < j ≤ bᵢ.
• Then count how many additional pairs arise under the interior‐meeting scenario, i.e. pairs (i,j) with
i < j, bᵢ < j, and bᵢ ≥ cⱼ.
One can count these in O(N log N) total (over all testcases) by a Fenwick (BIT) or Segment‐Tree approach:
Finally, total_friends = sumB + sumA′, where sumA′ is the Fenwick‐accumulated count of (i,j) that meet in the interior.
This algorithm runs in O(N log N) per test (where N is the size of that test). Since the sum of N over all T testcases is at most 2×10^5, the total run‐time is about O(N log N) ≈ 2×10^5 × log(2×10^5) which is acceptable.
Below is a complete Java implementation.
────────────────────────────────────────────────────────
javaimport java.util.*; import java.lang.*; import java.io.*; class Codechef { // Fenwick (BIT) for counting how many b[i] lie in a given range static class Fenwick { int n; long[] fenw; Fenwick(int n) { this.n = n; fenw = new long[n+1]; } // add "val" at index idx void update(int idx, long val) { for (; idx <= n; idx += idx & -idx) { fenw[idx] += val; } } // sum from 1..idx long query(int idx) { long s = 0; for (; idx > 0; idx -= idx & -idx) { s += fenw[idx]; } return s; } // sum in [l..r] long rangeQuery(int l, int r) { if (r < l) return 0; return query(r) - query(l-1); } } public static void main (String[] args) throws java.lang.Exception { FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out,false); int T = in.nextInt(); while(T-- > 0) { int N = in.nextInt(); int[] H = new int[N+1]; for(int i=1; i<=N; i++){ H[i] = in.nextInt(); } // 1) Compute b[i] = rightMax[i]: // largest index r >= i s.t. H[i..r] is distinct. int[] b = new int[N+1]; Arrays.fill(b, 0); // We'll do a right-to-left pass with a "lastOcc" & a pointer "end". int[] lastOccB = new int[N+1]; // heights up to N Arrays.fill(lastOccB, N+1); // "not seen yet" int end = N; for(int i=N; i>=1; i--) { if(lastOccB[H[i]] <= end) { end = Math.min(end, lastOccB[H[i]] - 1); } b[i] = end; lastOccB[H[i]] = i; } // 2) Compute c[i] = leftMax[i]: // smallest index L <= i s.t. H[L..i] is distinct. int[] c = new int[N+1]; Arrays.fill(c, 0); int[] lastOccC = new int[N+1]; // for left pass Arrays.fill(lastOccC, -1); int start = 1; for(int i=1; i<=N; i++){ if(lastOccC[H[i]] >= start){ start = lastOccC[H[i]] + 1; } c[i] = start; lastOccC[H[i]] = i; } // 3) sumB = sum over i of (b[i] - i) for b[i] >= i long sumB = 0; for(int i=1; i<=N; i++){ if(b[i] >= i) { sumB += (b[i] - i); } } // 4) count pairs that meet in the interior ("A'") // We want those (i,j) with i<j, b[i] < j, and b[i] >= c[j]. // We'll use Fenwicks for b[i]. Fenwick fenw = new Fenwick(N); long sumA = 0; int ptr = 1; // We'll iterate j from 1..N for(int j=1; j<=N; j++){ // Add all i < j into Fenwicks (if b[i] > i, meaning i can move at least 1 forward) while(ptr < j) { if(b[ptr] > ptr) { int pos = b[ptr]; // clamp to [1..N] anyway if(pos < 1) pos = 1; if(pos > N) pos = N; fenw.update(pos, 1L); } ptr++; } // Now query how many i have c[j] <= b[i] < j // i.e. b[i] in [c[j], j-1], if c[j] <= j-1 int leftBound = c[j]; int rightBound = j-1; if(leftBound <= rightBound) { sumA += fenw.rangeQuery(leftBound, rightBound); } } long ans = sumB + sumA; out.println(ans); } out.flush(); } // a fast input reader, typical for large input static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Explanation of key parts:
We compute array b[] (“rightMax”):
We compute array c[] (“leftMax”):
The sum ∑(b[i]−i) counts all pairs (i,j) with i<j ≤ b[i], i.e. those pairs that can “meet to the right” at j (or beyond).
For the “meet in the interior” situation, we collect all i in a Fenwick tree keyed by b[i], then for each j we query how many i < j have c[j] ≤ b[i] < j.
Physically this says:
– “b[i] < j” ensures [i..j] is not distinct.
– but “b[i] ≥ c[j]” means j can step backward at least one step (c[j] < j), and i’s forward‐distinct range and j’s backward‐distinct range do overlap, allowing an interior k.
Summing these two counts gives the total number of friendly pairs.