Hello 2020 B.New Year and Ascent Sequence

Hello 2020 B.New Year and Ascent Sequence

A sequence a=[a1,a2,…,al] of length l has an ascent if there exists a pair of indices (i,j) such that 1≤i<j≤l and ai<aj. For example, the sequence [0,2,0,2,0] has an ascent because of the pair (1,4), but the sequence [4,3,3,3,1] doesn’t have an ascent.

Let’s call a concatenation of sequences p and q the sequence that is obtained by writing down sequences p and q one right after another without changing the order. For example, the concatenation of the [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.

Examples

input

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

这题比较巧妙吧,我是将每个字符串分成两类:
1.含严格上升子序对的,并计数cnt1,答案直接加n
2.不含的也计数为cnt2,将首字母存入一个数组a,末字母存入一个数组b,将数组a排序,对每个数组b的元素,找到a中第一个大于它的元素的位置pos,然后答案加cnt2-pos+cnt1
一遍就过了(●’◡’●),AC代码如下:

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
typedef long long ll;
int main()
{
    int n;
    cin>>n;
    int s[N];
    int a[N],b[N],c[N];
    int len;
    int cnt1=0;
    int cnt2=0;
    for(int i=0;i<n;i++){
        scanf("%d",&len);
        int minn=1000005;
        for(int j=0;j<len;j++)
        {
            scanf("%d",&a[j]);
            {if(a[j]>minn) s[i]=1;}
            minn=min(a[j],minn);
        }
        if(s[i]==0) {s[i]=0;b[cnt2++]=a[0];}
        else cnt1++;
        c[i]=a[len-1];
    }
    sort(b,b+cnt2);
    ll ans=0;
    for(int i=0;i<n;i++){
        if(s[i]==1) ans+=n;
        else ans+=cnt2-(upper_bound(b,b+cnt2,c[i])-b)+cnt1;
    }
    cout<<ans;
    return 0;
}
发布了235 篇原创文章 · 获赞 13 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_43765333/article/details/103840430