BZOJ 4152 The Captain (Dijkstra 堆优化)

4152: [AMPPZ2014]The Captain

Time Limit: 20 Sec Memory Limit: 256 MB

Description
给定平面上的n个点,定义(x1,y1)到(x2,y2)的费用为min(|x1-x2|,|y1-y2|),求从1号点走到n号点的最小费用。

Input
第一行包含一个正整数n(2<=n<=200000),表示点数。
接下来n行,每行包含两个整数x[i],yi,依次表示每个点的坐标。

Output
一个整数,即最小费用。

Sample Input
5
2 2
1 1
4 5
7 1
6 7

Sample Output
2

思路:
晃眼是一道最短路的裸题,结果n是10^5级别,n^2不知道炸到哪儿去了。再仔细看看,呀,好像能贪心呢。
本来可以考虑每两个点之间连一条边 O(n^2)
但是如果两个点u,v之间连了一条x的边,中间还有一个点a,那么|x_u - x_a|+|x_a - x_v| = |x_u- x_v|那么就可以只连u到a的x的边和a到v的x的边,同理对于y的边,也只用连上面的点连中间的点,中间的点连下面的点,也就是说,一个点连出去的边只需要是上下左右距离最近的四个点。一下子就从n^2降到4*n可以存储的数量级了。于是分别按照x,y排序后连接的相邻的点。
用dijkstra跑一遍最短路,稳定的时间复杂度O(nlogn) 。
而spfa好像跑不过。。。
新技能get,STL的小根堆优化。

#include <vector>
#include <queue>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define LL long long
using namespace std;

const int N=2e5+10;

int n, idc;
int head[N], dis[N];
bool vis[N];

struct node{
    int x, y, ord;
}a[N];

struct ln{
    int to, next, w;
}ed[N<<2];

void adde(int u, int v, int w){
    ed[++idc].to = v; 
    ed[idc].next = head[u]; 
    head[u] = idc; 
    ed[idc].w = w;
    ed[++idc].to = u; 
    ed[idc].next = head[v]; 
    head[v] = idc; 
    ed[idc].w = w;
}

bool cmpx(node aa,node bb) {return aa.x < bb.x;}
bool cmpy(node aa,node bb) {return aa.y < bb.y;}

typedef pair<int, int> cc;
priority_queue<cc,vector<cc>,greater<cc> >Q;//小根堆 

int main(){
    scanf("%d", &n);
    for(int i=1; i<=n; i++){
        scanf("%d%d", &a[i].x, &a[i].y); 
        a[i].ord = i;
    } 
    sort(a+1, a+n+1, cmpx);
    for(int i=1; i<n; i++)
        adde(a[i].ord, a[i+1].ord, a[i+1].x - a[i].x);
    sort(a+1, a+n+1, cmpy);
    for(int i=1; i<n; i++)
        adde(a[i].ord, a[i+1].ord, a[i+1].y - a[i].y);//相邻x,y加边 
    memset(dis, 0x7f, sizeof(dis)); dis[1] = 0;
    Q.push( make_pair(0, 1) );
    while( !Q.empty() ){//Dijkstra堆优化,frist排序,second点 
        int x = Q.top().second; 
        Q.pop();
        if( vis[x] ) continue;
        vis[x] = 1;
        for(int k=head[x]; k; k=ed[k].next)
            if (dis[ed[k].to] > dis[x] + ed[k].w){
                dis[ed[k].to] = dis[x] + ed[k].w;
                Q.push( make_pair(dis[ed[k].to], ed[k].to) );
            }
    }
    printf("%d\n", dis[n]);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值