题目 | Hossam and Friends
Codeforces Round #837 (Div. 2)
B. Hossam and Friends
https://codeforces.com/contest/1771/problem/B
2 seconds / 256 megabytes
standard input / standard output
Problem
Hossam makes a big party, and he will invite his friends to the party.
He has
Hossam has a list of
A subsegment of the queue starting from the friend
Hossam wants to know how many pairs
Input
The input consists of multiple test cases. The first line contains a single integer
The first line of each test case contains two integer numbers
The
Note that pairs can be repeated.
It is guaranteed that the sum of
Output
For each test case print an integer — the number of good subsegments.
Example
Input
2
3 2
1 3
2 3
4 2
1 2
2 3
Output
4
5
Note
In the first example, the answer is
The good subsegments are:
[1]
[2]
[3]
[1, 2]
In the second example, the answer is
The good subsegments are:
[1]
[2]
[3]
[4]
[3, 4]
题解
记录方式
对于一对不认识的人
我们记录的方式为每一对中编号大的指向编号小的,如下图蓝色箭头表示的为
然后我们来考虑子序列是否合法,如上图橙色箭头。子序列
计算方式
我们知道了记录方式,那么如何快速地进行计算呢?我们首先把上图的箭头改为数组的记录方式,如下面的第一行。然后再从左到右取最大值,如下面的第二行:
这样对于每一个元素,它的下标作为右端点,第二行的数据就是子序列的左端点不能越过的下标。如
这样我们遍历一遍数组,就能得到答案为:
代码
#include <bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
const int MAXN = 1e5 + 10;
int n, m;
int a[MAXN];
void solve()
{
memset(a, 0, sizeof(a));
cin >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y;
cin >> x >> y;
if (x < y)
swap(x, y);
a[x] = max(a[x], y);
}
for (int i = 2; i <= n; i++)
a[i] = max(a[i], a[i - 1]);
int ans = 0;
for (int i = 1; i <= n; i++)
ans += i - a[i];
cout << ans << endl;
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while (t--)
solve();
return 0;
}
本文采用 CC BY-SA 4.0 许可,本文 Markdown 源码:Haotian-BiJi