A sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn’t have an ascent.
Let’s call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences p and q is denoted as p+q.
Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has n sequences s1,s2,…,sn which may have different lengths.
Gyeonggeun will consider all n2 pairs of sequences sx and sy (1≤x,y≤n), and will check if its concatenation sx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.
Please count the number of pairs (x,y) of sequences s1,s2,…,sn whose concatenation sx+sy contains an ascent.Input
The first line contains the number n (1≤n≤100000) denoting the number of sequences.
The next n lines contain the number li (1≤li) denoting the length of si, followed by li integers si,1,si,2,…,si,li (0≤si,j≤106) denoting the sequence si.
It is guaranteed that the sum of all li does not exceed 100000.Output
Print a single integer, the number of pairs of sequences whose concatenation has an ascent.Examplesinput
5 1 1 1 1 1 2 1 4 1 3
output
9
input
3 4 2 0 2 0 6 9 9 8 8 7 7 1 6
output
7
input
10 3 62 24 39 1 17 1 99 1 60 1 64 1 30 2 79 29 2 20 73 2 85 37 1 100
output
72
Note
For the first example, the following 9 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio( false ); cin.tie(0); int n; cin >> n; long long ans = ( long long ) n * n; vector<pair< int , int >> a; for ( int i = 0; i < n; i++) { int foo; cin >> foo; vector< int > b(foo); for ( int j = 0; j < foo; j++) { cin >> b[j]; } bool ok = true ; for ( int j = 0; j < foo - 1; j++) { ok &= b[j] >= b[j + 1]; } if (ok) { a.emplace_back(b[0], b.back()); } } vector<pair< int , int >> events; for ( auto & p : a) { events.emplace_back(p.first, -1); events.emplace_back(p.second, 1); } sort(events.begin(), events.end()); int balance = 0; for ( auto & p : events) { if (p.second == -1) { ++balance; } else { ans -= balance; } } cout << ans << '\n' ; return 0; } |