【2022年11月21日提高A组】 乐跑购物【BFS】

34 篇文章 0 订阅
18 篇文章 0 订阅

在这里插入图片描述

思路:

设fi,j表示从1到i,n到j,回文合法的最小边数,然后直接双端bfs

c o d e code code

#include<iostream>
#include<cstdio>
#include<map>
#include<queue>
#include<algorithm>
#include<cstring>
#define ll long long

using namespace std;

const ll MAXN = 1e3 + 10;

ll n, m, tot, head[MAXN];
struct node {
	ll to, next;
	char s;
}b[MAXN * 2];
struct abc {
	ll x, y;
	string s;
}a[MAXN * 2];
int v[MAXN][MAXN];

bool cmp(abc x, abc y) {
	if(x.x != y.x) return x.x < y.x;
	else if(x.y != y.y) return x.y < y.y;
	else return x.s < y.s;
}

void add(ll x, ll y, string s) {
	b[++ tot].to = y, b[tot].next = head[x];
	b[tot].s = s[0];
	head[x] = tot;
}

void bfs(ll s, ll t) {
	memset(v, -1, sizeof(v));
	queue<pair<ll, ll> > q;
	q.push(make_pair(s, t));
	v[s][t] = 0;
	while(!q.empty()) {
		int x = q.front().first, y = q.front().second;
		q.pop();
		for(int i = head[x]; i; i = b[i].next) {
			for(int j = head[y]; j; j = b[j].next) {
				if(b[i].s != b[j].s) continue;
				int xx = b[i].to, yy = b[j].to;
				if(v[xx][yy] != -1) continue;
				v[xx][yy] = v[x][y] + 1;
				q.push(make_pair(xx, yy));
			}
		}
	}
}

int main() {
	scanf("%lld%lld", &n, &m);
	for(ll i = 1; i <= m; i ++) {
		ll x, y;
		string s;
		cin>>a[i].x>>a[i].y>>a[i].s;
		if(a[i].x > a[i].y) swap(a[i].x, a[i].y);
	}
	sort(a + 1, a + 1 + m, cmp);
	for(ll i = 1; i <= m; i ++)
		if(a[i].x != a[i - 1].x || a[i].y != a[i - 1].y || a[i].s != a[i - 1].s) {
			add(a[i].x, a[i].y, a[i].s);
			add(a[i].y, a[i].x, a[i].s);
		}
	bfs(1, n);
	int ans = 1e9;
	for(int i = 1; i <= n; i ++)
		if(v[i][i] != -1) ans = min(v[i][i] * 2, ans); 
	for(int i = 1; i <= n; i ++)
		for(int j = head[i]; j; j = b[j].next) if(v[i][b[j].to] != -1) ans = min(v[i][b[j].to] * 2 + 1, ans);
	printf("%d", ans == 1e9 ? -1 : ans);
	return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值