http://hihocoder.com/problemset/problem/1138
很久不用最短路,几乎连基本性质也忘了,结果这道题就是某些最短路算法空间复杂度是o(n)
这里总结四种算法
算法名称 时间复杂度 空间复杂度
dijkstra+heap O(elog(e+n)) O(n)
bellman-ford O(ne) O(n)
spfa O(ke) O(n)
floyd-warshall O(n^3) O(n^2)
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn = 1e5 + 5;
const int maxm = 1e6 + 6;
int first[maxn],n;
struct edge
{
int t,c,nxt;
} e[maxm];
void addedge(int f,int t,int c,int ind)
{
e[ind].nxt = first[f];
e[ind].t = t;
e[ind].c = c;
first[f] = ind;
}
struct pnt
{
int x,y,id;
pnt()
{
x = y = id = 0;
}
pnt(int _x,int _y,int _id)
{
x = _x;
y = _y;
id = _id;
}
};
bool cmpx(pnt p1,pnt p2)
{
if(p1.x!= p2.x)return p1.x < p2.x;
return p1.y < p2.y;
}
bool cmpy(pnt p1,pnt p2)
{
if(p1.y!= p2.y)return p1.y < p2.y;
return p1.x < p2.x;
}
pnt a[maxn];
long long dis[maxn];
bool vis[maxn];
typedef pair<long long ,int> P;
priority_queue<P, vector <P>, greater<P> > que;
long long dijkstra()
{
for(int i = 0; i < n; i++)dis[i] = 2e18;
memset(vis,false,sizeof vis);
while(!que.empty())que.pop();
dis[0] = 0;
vis[0] = true;
for(int p = first[0]; p != -1; p = e[p].nxt)
{
int t = e[p].t;
dis[t] = e[p].c;
que.push(P(dis[t],t));
}
while(!que.empty())
{
int f = que.top().second;
que.pop();
if(f == n-1)break;
if(vis[f])continue;
vis[f] = true;
for(int p = first[f]; p != -1; p = e[p].nxt)
{
int t = e[p].t;
if(dis[t] > dis[f] + e[p].c){
dis[t] = dis[f] + e[p].c;
que.push(P(dis[t],t));
}
}
}
return dis[n - 1];
}
int main()
{
while(scanf("%d",&n)==1)
{
memset(first, -1, sizeof first);
for(int i = 0; i < n; i++)
{
scanf("%d%d",&a[i].x,&a[i].y);
a[i].id = i;
}
sort(a,a + n,cmpx);
for(int i = 0; i < n - 1; i++)
{
addedge(a[i].id,a[i + 1].id,
min(abs(a[i].x - a[i + 1].x),abs(a[i].y - a[i + 1].y)),2 * i);
addedge(a[i + 1].id,a[i].id,
min(abs(a[i].x - a[i + 1].x),abs(a[i].y - a[i + 1].y)),2 * i + 1);
}
sort(a,a + n,cmpy);
for(int i = 0; i < n - 1; i++)
{
addedge(a[i].id,a[i + 1].id,
min(abs(a[i].x - a[i + 1].x),abs(a[i].y - a[i + 1].y)),2 * i + 2 * n);
addedge(a[i + 1].id,a[i].id,
min(abs(a[i].x - a[i + 1].x),abs(a[i].y - a[i + 1].y)),2 * i + 1 + 2 * n);
}
long long ans = dijkstra();
printf("%lld\n",ans);
}
return 0;
}