Untitled
unknown
plain_text
a year ago
1.2 kB
0
Indexable
Never
import java.io.*; import java.util.*; class Pair { int val; int pos; Pair(int val, int pos) { this.val = val; this.pos = pos; } } public class Main { public static void main(String args[]) { Scanner input = new Scanner(System.in); int n = input.nextInt(); int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = input.nextInt(); } int left[] = new int[n], right[] = new int[n]; Stack<Pair> s = new Stack<>(); long ans = 0; for (int i = 0; i < n; i++) { while (s.empty() == false && a[i] < s.peek().val) { s.pop(); } if (s.empty()) { left[i] = i + 1; } else { left[i] = i - s.peek().pos; } s.push(new Pair(a[i], i)); } s = new Stack<>(); for (int i = n - 1; i >= 0; i--) { while (s.empty() == false && a[i] <= s.peek().val) { s.pop(); } if (s.empty()) { right[i] = n - i; } else { right[i] = s.peek().pos - i; } s.push(new Pair(a[i], i)); } for (int i = 0; i < n; i++) { ans += (long) left[i] * right[i] * a[i]; } System.out.println(ans); } }