【0】题解:AT_abc394_e [ABC394E] Palindromic Shortest Path
唉唐了没做出来。
考虑使用回文最短路。
先将 \((i,j)\) 相邻或 \((i,i)\) 相等加入队列。
然后通过让 \(i\) 跑反边到前驱,\(j\) 跑正边到后继,可以得出一条满足回文的最短路。
具体维护如下:
- 加入 \((i,i)\) 与有边的 \((i,j)\),这些状态一定是回文的。
- BFS,每一次枚举 \(i\) 的前驱,\(j\) 的后继,要是字符一致,就是合法的回文串扩展。
- 更新答案数组 \(dep\),注意每一次扩展状态其实本质是走 \(2\) 步。
#include<bits/stdc++.h>
using namespace std;
namespace ivan422{
#define ll long long
#define ld long double
#define il __int128
#define fl __float128
#define x0 x_0
#define x1 x_1
#define y0 y_0
#define y1 y_1
#define yn y_n
#define j0 j_0
#define j1 j_1
#define k0 k_0
#define k1 k_1
#define d0 d_0
#define d1 d_1
#define pb push_back
#define pf push_front
#define mp make_pair
#define ar array<int,3>
#define us unsigned
#define io ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
};
using namespace ivan422;
const int N=125+10,M=125+10;
const int P1=1e9+7,P9=998244353;
const double pi=3.1415926535,eps=1e-7;
int n,dep[M][M];
char c[M][M];
queue<array<int,2> >q;
signed main(){
cin>>n;
for(int i=1;i<=n;i++)for(int j=1;j<=n;j++)cin>>c[i][j];
memset(dep,0x7f,sizeof(dep));
for(int i=1;i<=n;i++){
dep[i][i]=0;
q.push({i,i});
}
for(int i=1;i<=n;i++)for(int j=1;j<=n;j++)if(i!=j){
if(c[i][j]!='-'){
dep[i][j]=1;
q.push({i,j});
}
}
while(q.size()){
array<int,2>f=q.front();
q.pop();
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(c[i][f[0]]=='-'||c[f[1]][j]=='-')continue;
if(c[i][f[0]]!=c[f[1]][j])continue;
if(dep[i][j]==dep[0][0]){
dep[i][j]=dep[f[0]][f[1]]+2;
q.push({i,j});
}
}
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++)cout<<(dep[i][j]==dep[0][0]?-1:dep[i][j])<<" ";
cout<<"\n";
}
return 0;
}

浙公网安备 33010602011771号