C. Foe Pairs
You are given a permutation p of length n. Also you are given m foe pairs (ai, bi) (1 ≤ ai, bi ≤ n, ai ≠ bi). Your task is to count the number of different intervals (x, y) (1 ≤ x ≤ y ≤ n) that do not contain any foe pairs. So you shouldn't count intervals (x, y) that contain at least one foe pair in it (the positions and order of the values from the foe pair are not important). Consider some example: p = [1, 3, 2, 4] and foe pairs are {(3, 2), (4, 2)}. The interval (1, 3) is incorrect because it contains a foe pair (3, 2). The interval (1, 4) is also incorrect because it contains two foe pairs (3, 2) and (4, 2). But the interval (1, 2) is correct because it doesn't contain any foe pair.
解法
题目中好像没有说明每个pi是不同的,当我们知道这个那我们可以直接记录每个数字出现的位置,然后再m次输入敌对数对的时候更新数组mi(以i开始最多能到达的位置),然后反向遍历更新一下就行了
Code
void solve()
{
int n, m; cin >> n >> m;
VI a(n + 1); rep (i, 1, n) cin >> a[i];
VI b(n + 1), mi(n + 2, n);
rep (i, 1, n) b[a[i]] = i;
rep (i, 1, m) {
int l, r; cin >> l >> r;
l = b[l], r = b[r];
if (l > r) swap(l, r);
mi[l] = min(mi[l], r - 1);
}
per (i, 1, n) mi[i] = min(mi[i], mi[i + 1]);
ll res = 0;
rep (i, 1, n) res += mi[i] - i + 1;
cout << res << endl;
}
D. Nested Segments
You are given n segments on a line. There are no ends of some segments that coincide. For each segment find the number of segments it contains.
解法
我们对区间排序然后用树状数组去存有区间因为我们的左区间是递增的所有我们直接遍历即可这样我们就成了直接在树状数组总找>=l&&<=r的有多少个答
Code
struct Fenwick {
const int n;
std::vector<int> a;
Fenwick(int n) : n(n), a(n) {}
void add(int x, int v) {
for (int i = x + 1; i <= n; i += i & -i) {
a[i - 1] += v;
}
}
int query(int x) {
int ans = 0;
for (int i = x; i > 0; i -= i & -i) {
ans += a[i - 1];
}
return ans;
}
};
void solve()
{
int n; cin >> n;
vector<array<int, 3>> a(n + 1);
vector<int> v;
Fenwick bit(n * 2);
rep (i, 1, n) {
int l, r; cin >> l >> r;
v.pb(l), v.pb(r);
a[i] = {l, r, i};
}
sort(all(v));
v.erase(unique(all(v)), v.end());
auto find = [&] (int x) {
return lower_bound(all(v), x) - v.begin() + 1;
};
rep (i, 1, n) {
a[i][0] = find(a[i][0]);
a[i][1] = find(a[i][1]);
}
rep (i, 1, n) {
bit.add(a[i][1], 1);
}
vector<int> res(n + 1);
sort(a.begin() + 1, a.end());
for (int i = 1; i <= n; i++) {
auto [l, r, idx] = a[i];
res[idx] = bit.query(r) - bit.query(l);
bit.add(r, -1);
}
rep (i, 1, n) cout << res[i] << "\n";
}