题解
一看就是一道最短路的题。设起点、终点,按题意一条条地添边。每层楼都是环状的,终点在第N+1层,添边时要格外小心。有点分层图的意思。堆优化dijkstra耐心写下去。本题考最短路,还考耐心。Code
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int oo = 1000000000, nil = 0;
int N, M, map[65][65];
struct Point
{
int h, n;
Point(int h = 0, int n = 0) :h(h), n(n) {}
};
Point u[20000], v[20000], S, T;
int e, w[20000], nxt[20000], pnt[65][65];
int d[65][65];
bool can[65][65], vis[65][65];
void addedge(Point a, Point b, int c)
{
u[++e] = a; v[e] = b; w[e] = c;
nxt[e] = pnt[a.h][a.n]; pnt[a.h][a.n] = e;
}
void init()
{
int opt;
memset(can, 0, sizeof(can));
memset(w, 0, sizeof(w));
memset(nxt, 0, sizeof(nxt));
memset(pnt, 0, sizeof(pnt));
e = 0;
scanf("%d%d", &N, &M);
for(int i = 0; i < N; ++i)
{
for(int j = 0; j < M; ++j)
{
scanf("%d%d", &opt, &map[i][j]);
if(opt == 1)
{
can[i][j] = true;
}
}
}
for(int i = 0; i < N; ++i)
{
for(int j = 0; j < M; ++j)
{
addedge(Point(i, j), Point(i, (j + 1) % M), map[i][(j + 1) % M]);
addedge(Point(i, (j + 1) % M), Point(i, j), map[i][j]);
opt = j - 1;
if(opt < 0)
{
opt = M - 1;
}
addedge(Point(i, j), Point(i, opt), map[i][opt]);
addedge(Point(i, opt), Point(i, j), map[i][j]);
if(can[i][j])
{
addedge(Point(i, j), Point(i + 1, j), map[i + 1][j]);
}
}
}
S = Point(N - 1, M);
T = Point(N, M);
for(int i = 0; i < M; ++i)
{
addedge(S, Point(0, i), map[0][i]);
}
for(int i = 0; i < M; ++i)
{
addedge(Point(N, i), T, 0);
}
}
struct node : public Point
{
int d;
node(int xh = 0, int xn = 0, int xd = 0)
{
h = xh; n = xn; d = xd;
}
bool operator < (const node& b) const
{
return d > b.d;
}
};
void work()
{
memset(d, 0x3f, sizeof(d));
memset(vis, 0, sizeof(vis));
priority_queue <node> Q;
d[S.h][S.n] = 0;
vis[S.h][S.n] = 1;
Q.push(node(S.h, S.n, 0));
while(!Q.empty())
{
node t = Q.top();
Q.pop();
for(int j = pnt[t.h][t.n]; j != nil; j = nxt[j])
{
if((!vis[v[j].h][v[j].n]) && d[v[j].h][v[j].n] > t.d + w[j])
{
d[v[j].h][v[j].n] = t.d + w[j];
vis[v[j].h][v[j].n] = true;
Q.push(node(v[j].h, v[j].n, d[v[j].h][v[j].n]));
}
}
}
if(d[T.h][T.n] > oo)
{
puts("-1");
}
else
{
printf("%d\n", d[T.h][T.n]);
}
}
int main()
{
init();
work();
return 0;
}