跳到正文

个人记录

图论-最短路-p4011(拆点基础 dp 01bfs)

_Gakki_约 5 分钟
原文
文章信息与版本

文章信息

发布
2021年3月8日
收录
2025年12月12日
更新
2026年11月7日
篇幅
约 5 分钟

版本

  1. v1当前

思路:我们不能够知道在一个位置是有没有钥匙所以我们可以考虑为问题增加一个维度state(01串)利用状态压缩的思想存储是否拥有某把钥匙那么可得转移方程如下:

1.当前位置有钥匙把钥匙捡起来。

2.当前位置可以走过去就走过去如果有门检查一下是否有钥匙没有则走不过去。

我们可以把位置压缩成一维的得到状态为d[pos][state] 那么有钥匙d[pos][state] = d[pos][state|1<<key]

没有如果可以走过去d[pos] = d[pos_next][state] 不难发现直接使用dp因为环难以确定状态的先后顺序故考虑最短路而由于只有0和1的权值我们使用 01bfs

实现细节:由于恶心的输入我们使用set来判断一个边是否在之前出现过之后再建图

C++
#include<bits/stdc++.h> 
using namespace std;

const int maxn = 150,maxm = 500,maxp = 1<<10;

int head[maxn];
struct edge{
	int to,next,w;
}e[maxm];
int vis[maxn][maxp];
int dis[maxn][maxp];
int n,m,p,cnt;
int g[maxn][maxn];
int key[maxn];
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};

struct node{
	int x,y;
	bool operator < (const node s) const{
		if(x != s.x)return x < s.x;
		return y < s.y;
	}
};

set<node> se;
void add_edge(int u,int v,int w){
	edge temp;temp.to = v,temp.w = w;
	e[++cnt] = temp;
	e[cnt].next = head[u];
	head[u] = cnt;
}

void build(){
	for(int i = 1;i <= n;i++){
		for(int j = 1;j <= m;j++){
			for(int k = 0;k < 4;k++){
				int x = i+dx[k],y = j+dy[k];
				if(x <= 0 || x > n || y <= 0 || y > m) continue;
				node temp;temp.x = g[i][j],temp.y = g[x][y];
				if(!se.count(temp)) add_edge(g[i][j],g[x][y],0);//相邻的位置建边0表示不需要钥匙 
				//已经建过或者有墙就不需要建了 
			}
		}
	}
}

int bfs(){
	memset(dis,0x3f,sizeof(dis));
	dis[1][0] = 0;
	deque<node> q;
	node temp;temp.x = 1,temp.y = 0;
	q.push_back(temp);
	while(!q.empty()){
		node t1 = q.front();
		q.pop_front();
		if(vis[t1.x][t1.y]) continue;
		vis[t1.x][t1.y] = 1;
		if(t1.x == n*m) return dis[t1.x][t1.y];
		if(key[t1.x]){//有钥匙的情况 
			int state = t1.y | key[t1.x];
			if(dis[t1.x][state] > dis[t1.x][t1.y]){
				dis[t1.x][state] = dis[t1.x][t1.y];
				node temp;temp.x = t1.x,temp.y = state;
				q.push_front(temp);
			}
		}
		for(int i = head[t1.x];i != -1;i = e[i].next){
			int to = e[i].to;
			if(e[i].w && !(t1.y>>e[i].w - 1 & 1)) continue;//如果是门我们没有钥匙跳过 
			if(dis[to][t1.y] > dis[t1.x][t1.y]+1){//正常行进 
				dis[to][t1.y] = dis[t1.x][t1.y]+1;
				node temp;temp.x = to,temp.y = t1.y;
				q.push_back(temp);
			}
		}
	}
	return -1;
}

int main(){
	std::ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
	cin>>n>>m>>p;
	memset(head,-1,sizeof(head));
	for(int i = 1,t = 1;i <= n;i++){
		for(int j = 1;j <= m;j++){
			g[i][j] = t++;//方便对位置进行降维的数组 
		}
	}
	int k;cin>>k;
	while(k--){
		int x1,y1,x2,y2,c;
		cin>>x1>>y1>>x2>>y2>>c;
		int t1 = g[x1][y1],t2 = g[x2][y2];
		node temp;temp.x = t1,temp.y = t2;
		se.insert(temp);temp.x = t2,temp.y = t1;
		se.insert(temp);//先把当前的边建好并进行判重 
		if(c >= 1){//边的权重表示需要的钥匙的id 
			add_edge(t1,t2,c);
			add_edge(t2,t1,c);
		}
	}
	build();
	int s;
	cin>>s;
	while(s--){
		int x,y,c;
		cin>>x>>y>>c;
		key[g[x][y]] |= 1 << c - 1;//存储钥匙 
	}
	cout<<bfs()<<endl;
    return 0;
}
原文