BZOJ 4152 The Captain

Posted on 2016-04-07 20:30  ziliuziliu  阅读(182)  评论(0编辑  收藏  举报

切比雪夫距离最短路。

按x,y轴分别排序然后相邻点连边跑最短路。

spfa会被卡掉。

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<queue>
#define maxv 200500
#define maxe 805000
#define inf 999999999999999
using namespace std;
struct point
{
    long long x,y,id;
}p[maxv];
struct edge
{
    long long v,w,nxt;    
}e[maxe];
struct status
{
    long long v,len;
    bool operator < (const status &a) const
    {
        return len>a.len;
    }
};
priority_queue <status> q;
long long n,g[maxv],dis[maxv],nume=0;
bool vis[maxv];
bool cmp1(point a,point b)
{
    return a.x<b.x;
}
bool cmp2(point a,point b)
{
    return a.y<b.y;
}
void addedge(long long u,long long v,long long w)
{
    e[++nume].v=v;
    e[nume].w=w;
    e[nume].nxt=g[u];
    g[u]=nume;
}
void dijkstra()
{
    while (!q.empty())
        q.pop();
    for (int i=2;i<=n;i++)
        dis[i]=inf;
    dis[1]=0;
    status begin;begin.v=1;begin.len=0;q.push(begin);
    while (!q.empty())
    {
        status head=q.top();q.pop();
        long long now=head.v;
        if (dis[now]!=head.len) continue;
        for (long long i=g[now];i;i=e[i].nxt)
        {
            long long v=e[i].v;
            if (dis[v]>dis[now]+e[i].w)
            {
                dis[v]=dis[now]+e[i].w;
                status then;then.v=v;then.len=dis[v];
                q.push(then);
            }
        }
    }
}
int main()
{
    scanf("%lld",&n);
    for (long long i=1;i<=n;i++)
    {
        scanf("%lld%lld",&p[i].x,&p[i].y);
        p[i].id=i;
    }
    sort(p+1,p+n+1,cmp1);
    for (long long i=1;i<=n-1;i++)
    {
        addedge(p[i].id,p[i+1].id,p[i+1].x-p[i].x);
        addedge(p[i+1].id,p[i].id,p[i+1].x-p[i].x);
    }
    sort(p+1,p+n+1,cmp2);
    for (long long i=1;i<=n-1;i++)
    {
        addedge(p[i].id,p[i+1].id,p[i+1].y-p[i].y);
        addedge(p[i+1].id,p[i].id,p[i+1].y-p[i].y);
    }
    dijkstra();
    printf("%lld\n",dis[n]);
    return 0;
}