4152: [AMPPZ2014]The Captain
Time Limit: 20 Sec Memory Limit: 256 MBSubmit: 849 Solved: 324
[ Submit][ Status][ Discuss]
Description
给定平面上的n个点,定义(x1,y1)到(x2,y2)的费用为min(|x1-x2|,|y1-y2|),求从1号点走到n号点的最小费用。
Input
第一行包含一个正整数n(2<=n<=200000),表示点数。
接下来n行,每行包含两个整数x[i],y[i](0<=x[i],y[i]<=10^9),依次表示每个点的坐标。
Output
一个整数,即最小费用。
Sample Input
5
2 2
1 1
4 5
7 1
6 7
2 2
1 1
4 5
7 1
6 7
Sample Output
2
HINT
Source
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
#include<ext/pb_ds/priority_queue.hpp>
using namespace std;
const int maxn = 2E5 + 20;
typedef long long LL;
const LL INF = 1E16;
struct E{
int to,w; E(){}
E(int to,int w): to(to),w(w){}
};
struct Point{
int Num,x,y; Point(){}
Point(int Num,int x,int y): Num(Num),x(x),y(y){}
}p[maxn];
struct data{
int Num; LL d; data(){}
data(int Num,LL d): Num(Num),d(d){}
bool operator < (const data &b) const {return d > b.d;}
};
typedef __gnu_pbds::priority_queue<data,less<data>,__gnu_pbds::pairing_heap_tag> Heap;
LL dis[maxn];
int n;
bool inq[maxn];
vector <E> v[maxn];
Heap Q;
Heap::point_iterator id[maxn];
bool cmpx(const Point &A,const Point &B) {return A.x < B.x;}
bool cmpy(const Point &A,const Point &B) {return A.y < B.y;}
int getint()
{
char ch = getchar(); int ret = 0;
while (ch < '0' || '9' < ch) ch = getchar();
while ('0' <= ch && ch <= '9')
ret = ret*10 + ch - '0',ch = getchar();
return ret;
}
int main()
{
#ifdef DMC
freopen("DMC.txt","r",stdin);
#endif
n = getint();
for (int i = 1; i <= n; i++)
{
int x = getint(),y = getint();
p[i] = Point(i,x,y);
}
sort(p + 1,p + n + 1,cmpx);
for (int i = 1; i < n; i++)
{
v[p[i].Num].push_back(E(p[i+1].Num,p[i+1].x - p[i].x));
v[p[i+1].Num].push_back(E(p[i].Num,p[i+1].x - p[i].x));
}
sort(p + 1,p + n + 1,cmpy);
for (int i = 1; i < n; i++)
{
v[p[i].Num].push_back(E(p[i+1].Num,p[i+1].y - p[i].y));
v[p[i+1].Num].push_back(E(p[i].Num,p[i+1].y - p[i].y));
}
id[1] = Q.push(data(1,0)); inq[1] = 1;
for (int i = 2; i <= n; i++) dis[i] = INF;
while (!Q.empty())
{
int k = Q.top().Num; Q.pop();
for (int i = 0; i < v[k].size(); i++)
{
E e = v[k][i];
if (dis[e.to] > dis[k] + 1LL * e.w)
{
dis[e.to] = dis[k] + 1LL * e.w;
if (!inq[e.to]) id[e.to] = Q.push(data(e.to,dis[e.to]));
else Q.modify(id[e.to],data(e.to,dis[e.to]));
}
}
}
cout << dis[n] << endl;
return 0;
}