ZOJ 3862 Intersection【貪心】【幾何】【模擬】

題目鏈接

http://icpc.moe/onlinejudge/showProblem.do?problemId=5474

思路

題意是給你很多條線段,你可以交換任意兩個點,叫你給出一種交換序列,使得最後沒有兩條線段是相交的。

這裏要貪心一下,就是把點按x小優先,x相等y大優先排好序,然後兩個兩個連起來。
如下圖:

這裏寫圖片描述

至於怎麼把兩個點連起來,只用交換這兩個點 其中一個點,和另一個點的相連點 即可。

AC代碼

#include <iostream>
#include <cstdio>
#include <set>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>
#include <map>
using namespace std;

struct node_t
{
    int x, y;
    int id;
    int to;
    bool friend operator < (node_t a, node_t b)
    {
        if (a.x == b.x)return a.y>b.y;
        return a.x < b.x;
    }
}
node[200000 + 100];

int pos[200000 + 100];
pair<int, int>ans[200000 + 200];
int main()
{
    int T;
    scanf("%d", &T);
    while (T--)
    {
        int cnt_ans = 0;
        memset(pos, 0, sizeof pos);
        int n;
        scanf("%d", &n);
        for (int i = 1; i <= 2 * n; ++i)
        {
            int x, y;
            scanf("%d%d", &x, &y);
            node[i].x = x; 
            node[i].y = y;
            node[i].id = i;
        }
        for (int i = 1; i <= n; ++i)
        {
            int a, b;
            scanf("%d%d", &a, &b);
            node[a].to = b;
            node[b].to = a;
        }
        sort(node + 1, node + 1 + 2 * n);
        for (int i = 1; i <= 2 * n; ++i)
        {
            pos[node[i].id] = i;
        }
        for (int i = 1; i < 2 * n; i += 2)
        {
            if (node[i].to == node[i + 1].id && node[i + 1].to == node[i].id);
            else
            {
                ans[cnt_ans++] = make_pair(node[i].id, node[pos[node[i + 1].to]].id);
                int id1 = node[i].id, id2 = node[i + 1].to;
                int pos2 = pos[id2];
                swap(node[i].id, node[pos2].id);
                swap(node[i].to, node[pos2].to);
                pos[id1] = pos2;
                pos[id2] = i;
            }
        }
        printf("%d\n", cnt_ans);
        for (int i = 0; i < cnt_ans; ++i)
        {
            printf("%d %d\n", ans[i].first, ans[i].second);
        }
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章