G. Trace(ACM-ICPC 2018 徐州賽區網絡預賽,思路,set)

描述

There’s a beach in the first quadrant. And from time to time, there are sea waves. A wave ( xx , yy ) means the wave is a rectangle whose vertexes are ( 00 , 00 ), ( xx , 00 ), ( 00 , yy ), ( xx , yy ). Every time the wave will wash out the trace of former wave in its range and remain its own trace of ( xx , 00 ) -> ( xx , yy ) and ( 00 , yy ) -> ( xx , yy ). Now the toad on the coast wants to know the total length of trace on the coast after n waves. It’s guaranteed that a wave will not cover the other completely.

Input

The first line is the number of waves n(n \le 50000)n(n≤50000).

The next nn lines,each contains two numbers xx yy ,( 0 < x0

Output

An Integer stands for the answer.

Hint:

As for the sample input, the answer is 3+3+1+1+1+1=103+3+1+1+1+1=10

img

樣例輸入

3
1 4
4 1
3 3

樣例輸出

10

題目來源

ACM-ICPC 2018 徐州賽區網絡預賽

思路

題目定義了海的波浪是一個矩形,每一次給定一個座標,波浪就會形成一個原點和當前點的矩形。一浪接着一浪,新的矩形就可能部分覆蓋住原來的矩形,題目保證任意兩個矩形都不相互覆蓋,現在求在經過n次波浪之後,現在留下來的矩形的邊長是多少。

因爲題目保證了兩個矩形一定不相互完全覆蓋。我們知道新的波浪會覆蓋以前的波浪,那麼最後一個波浪一定沒有被覆蓋,是完整的矩形,所以我們先存一下每個波浪的座標,然後倒着來。

用兩個set來維護矩形的橫座標和縱座標,首先把0插入到兩個set之中,然後每一次查詢比當前橫縱座標小的第一個值(可以先用set.lower_bound查出大於等於它的第一個數,然後迭代器–),由於題目保證了不相互覆蓋,那麼查到的橫縱座標的差的絕對值就可以累加到答案中,然後再把當前的橫縱座標插入.

累加完成後就是答案。

代碼

#include <bits/stdc++.h>
using namespace std;
#define mem(a, b) memset(a, b, sizeof(a))
typedef long long ll;
typedef pair<int, int> pir;
const int N = 1e5 + 10;
struct node
{
    int a, b;
} e[N];
set<int> sx, sy;
int main()
{
    //freopen("in.txt", "r", stdin);
    int n, a, b;
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
    {
        scanf("%d%d", &a, &b);
        e[i].a = a, e[i].b = b;
    }
    sx.insert(0), sy.insert(0);
    ll ans = 0;
    for (int i = n; i >= 1; i--)
    {
        a = e[i].a, b = e[i].b;
        auto it = sx.lower_bound(a);
        --it;
        ans += (a - *it);
        sx.insert(a);
        it = sy.lower_bound(b);
        --it;
        ans += (b - *it);
        sy.insert(b);
    }
    printf("%lld\n", ans);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章