#include<cstring>
#include<iostream>
#include<algorithm>
#include<deque>
#include<set>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
const int N = 20, M = 900, P = 1 << 10;
int n, m, p, k;
int h[N * N], e[M], ne[M], idx, w[M];
int g[N][N], key[N * N], dist[N * N][P];
bool st[N * N][P];
set<PII> edges;
void add(int a, int b, int c){
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx ++ ;
}
void build(){
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
for(int i = 1; i <= n; i ++ )
for(int j = 1; j <= m; j ++ )
for(int u = 0; u < 4; u ++ ){
int x = i + dx[u], y = j + dy[u];
if(!x || x > n || !y || y > m) continue;
int a = g[i][j], b = g[x][y];
if(edges.count({a, b}) == 0) add(a, b, 0);
}
}
int bfs(){
memset(dist, 0x3f, sizeof dist);
deque<PII> q;
q.push_back({1, 0});
dist[1][0] = 0;
while(q.size()){
PII t = q.front();
q.pop_front();
if(st[t.x][t.y]) continue;
st[t.x][t.y] = true;
if(t.x == m * n) return dist[t.x][t.y];
if(key[t.x]){
int state = t.y | key[t.x];
if(dist[t.x][state] > dist[t.x][t.y]){
dist[t.x][state] = dist[t.x][t.y];
q.push_front({t.x, state});
}
}
for(int i = h[t.x]; ~i; i = ne[i]){
int j = e[i];
if(w[i] && !(t.y >> w[i] - 1 & 1)) continue;
if(dist[j][t.y] > dist[t.x][t.y] + 1){
dist[j][t.y] = dist[t.x][t.y] + 1;
q.push_back({j, t.y});
}
}
}
return -1;
}
int main(){
scanf("%d%d%d%d", &n, &m, &p, &k);
memset(h, -1, sizeof h);
for(int i = 1, t = 1; i <= n; i ++ )
for(int j = 1; j <=m ; j ++ )
g[i][j] = t ++ ;
while(k -- ){
int x1, y1, x2, y2, c;
scanf("%d%d%d%d%d", &x1, &y1, &x2, &y2, &c);
int a = g[x1][y1], b = g[x2][y2];
edges.insert({a, b}), edges.insert({b, a});
if(c) add(a, b, c), add(b, a, c);
}
build();
int s;
scanf("%d", &s);
while(s -- ){
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
key[g[a][b]] |= 1 << c - 1;
}
printf("%d\n", bfs());
return 0;
}
求解hdu4845
该代码实现了一个基于BFS的算法,用于寻找带权重有向图中起点到终点的最短路径。程序首先读取图的节点数、边数、墙的位置和权重,然后通过添加边来构建图。接着,它进行广度优先搜索,更新每个节点的状态并计算最短路径。最后,输出从起点到终点的最短路径长度。
摘要由CSDN通过智能技术生成