您的位置:首页 > 大数据 > 人工智能

BZOJ 4152 The Captain (Dijkstra 堆优化)

2017-07-04 21:04 477 查看

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
, dis
;
bool vis
;

struct node{
int x, y, ord;
}a
;

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
);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: