[POI2009]Baj 最短回文路 BFS

本文介绍了一种解决图中寻找最短回文路径问题的算法,通过改进的广度优先搜索(BFS)策略,将时间复杂度从m^2降低至nm。文中详细解释了算法原理,并提供了完整的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description
N个点用M条有向边连接,每条边标有一个小写字母。 对于一个长度为D的顶点序列,回答每对相邻顶点Si到Si+1的最短回文路径。 如果没有,输出-1。 如果有,输出最短长度以及这个字符串。


Sample Input
6 7
1 2 a
1 3 x
1 4 b
2 6 l
3 5 y
4 5 z
6 5 a
3
1 5 3


Sample Output
3
-1


首先有一个比较显然的bfs,你可以从一个点或一条边开始往两边拓展,每次选择两条相同的边拓展出去,这样子时间复杂度是m^2的。
然后你其实可以这样拓,每次先拓展A,再让B跟着A拓展,这样的话时间复杂度可以降到nm,因为你考虑一条边a ->b,他可以由状态(c,a)转移过来,a是固定的,因此最多只有n个不同的状态。


#include <queue>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;
typedef long long LL;
int _min(int x, int y) {return x < y ? x : y;}
int _max(int x, int y) {return x > y ? x : y;}
int read() {
	int s = 0, f = 1; char ch = getchar();
	while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = getchar();}
	while(ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
	return s * f;
}

struct bfss {
	int x, y, c, dep;
	bfss() {}
	bfss(int _x, int _y, int _c, int _dep) {x = _x, y = _y, c = _c, dep = _dep;}
}; queue<bfss> q;
struct edge {
	int x, c, y, next;
} e[420000], e2[420000]; int len, len2, last[410][30], last2[410][30];
int hh[410][410][30], f[410][410], uu[410][410][30];
char ss[5];

void ins(int x, int c, int y) {
	e[++len].x = x, e[len].c = c, e[len].y = y;
	e[len].next = last[x][c], last[x][c] = len;
	e2[++len2].x = y, e2[len2].c = c, e2[len2].y = x;
	e2[len2].next = last2[y][c], last2[y][c] = len2;
}

int main() {
	int n = read(), m = read();
	for(int i = 1; i <= m; i++) {
		int x = read(), y = read();
		scanf("%s", ss + 1);
		hh[x][y][ss[1] - 'a' + 1] = 1;
	} 
	memset(f, -1, sizeof(f)); memset(uu, -1, sizeof(uu));
	for(int i = 1; i <= n; i++) q.push(bfss(i, i, -1, 0)), f[i][i] = 0;
	for(int i = 1; i <= n; i++) {
		for(int j = 1; j <= n; j++) {
			int u = 0;
			for(int k = 1; k <= 26; k++) if(hh[i][j][k]){
				ins(i, k, j);
				if(i != j) u = 1;
			} if(u) q.push(bfss(i, j, -1, 1)), f[i][j] = 1;
		}
	}
	while(!q.empty()) {
		bfss o = q.front(); q.pop();
		if(o.c == -1) {
			int x = o.x;
			for(int c = 1; c <= 26; c++) {
				for(int k = last2[x][c]; k; k = e2[k].next) {
					int i = e2[k].y;
					if(uu[i][o.y][c] == -1) {
						uu[i][o.y][c] = o.dep + 1;
						q.push(bfss(i, o.y, c, o.dep + 1));
					}
				}
			}
		} else {
			int x = o.y;
			for(int k = last[x][o.c]; k; k = e[k].next) {
				int i = e[k].y;
				if(f[o.x][i] == -1) {
					f[o.x][i] = o.dep + 1;
					q.push(bfss(o.x, i, -1, o.dep + 1));
				}
			}
		}
	} int p = read(); p--;
	int last = read();
	while(p--) {
		int x = read();
		printf("%d\n", f[last][x]);
		last = x;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值