思路:
设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;
}