不知道为什么题单里会有这个题……
题意
给你一个无向图,每条边上有一个字符,问你能不能从 走到 并且路上经过的字符构成一个回文串。可以就求最短路,不可以就输出 。
思路
简单双向 BFS 题。
两头一起搜,如果有字符相同的路就向前。
设现在的首尾搜过来的点分别为 和 ,每头已经走了 步。
如果 ,那么这组方案总步数(即回文串长度)为 。
如果 和 相邻,那么这组方案总步数为 ,判断是否相邻可以用 set。
否则找字符相同的路继续向前走。
总时间复杂度为 ,具体见代码。
代码
#include<bits/stdc++.h>
#define int long long
#define ull unsigned long long
#define endl "\n"
#define pb push_back
#define gc getchar
#define is isdigit
#define dou(___) cout<<fixed<<setprecision(___)
#define use_rng mt19937 rng(time(0))
using namespace std;
inline int rd(){int f=1,p=0;char c=gc();while(!is(c)&&c!=45)c=gc();
if(c==45)f=-1,c=gc();while(is(c))p=(p<<3)+(p<<1)+(c^48),c=gc();return f*p;}
const int inf=LLONG_MAX-1;
int n,m;
char c;
vector<pair<int,char>> e[1005];
set<int> s[1005];
queue<tuple<int,int,int>> q;
bool f[1005][1005];
signed main(){
ios_base::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
n=rd(),m=rd();
for(int i=1,u,v;i<=m;i++)
u=rd(),v=rd(),c=gc(),e[u].pb({v,c}),e[v].pb({u,c}),s[u].insert(v),s[v].insert(u);
q.push({0,1,n});
while(!q.empty())
{
auto [cnt,l,r]=q.front();q.pop();
if(l==r)cout<<cnt*2,exit(0);
if(s[l].count(r))cout<<cnt*2+1,exit(0);
for(auto [v1,c1]:e[l])
for(auto [v2,c2]:e[r])
if(!f[v1][v2]&&c1==c2)q.push({cnt+1,v1,v2}),f[v1][v2]=f[v2][v1]=1;
}
cout<<-1;
return 0;
}