Codeforces Hello 2020 B. New Year and Ascent Sequence(二分查找)

本文探讨了如何通过计算不包含升序对的序列组合数量,来间接解决寻找具有升序对的序列组合总数的问题。介绍了算法的具体实现过程,包括序列最小值与最大值的存储、排序以及使用二分查找来确定无升序对的数量。

题目链接:https://codeforc.es/contest/1284/problem/B

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

题意

给出 n 个数列,求有几种两个数列合起来之后有上升序列(数列可以从左结合也可以从右结合)

分析

我们可以反向先求出结合后不存在上升序列的情况的数量,然后所有情况减去这个数量就是答案。
先分别存数列的最小值和最大值,然后将最小值升序排序,遍历最大值,再用二分就能找出最小值大于最大值的数量,即无上升序列的情况的数量。

代码
#include<bits/stdc++.h>
using namespace std;

int n;
int l;
int a[1000007];
int minn[1000007],maxn[1000007],cnt;

int cmp(int x,int y)
{
	return x > y;
}

int main()
{
	scanf("%d",&n);
	long long ans = 0;
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&l);
		int flag = 0;
		for(int j=1;j<=l;j++)
		{
			scanf("%d",&a[j]);
			if(j == 1)
				continue;
			if(a[j] > a[j - 1]) flag = 1;
		}
		if(flag == 0)
		{
			minn[++cnt] = a[l];
			maxn[cnt] = a[1];
		}
	}
	sort(minn + 1, minn + 1 + cnt);
	for(int i=1;i<=cnt;i++)
	{
		int pos = lower_bound(minn + 1, minn + 1 + cnt, maxn[i]) - minn - 1;
		ans += cnt - pos;
	}
	printf("%lld",1ll * n * n - ans);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值