CF1495D BFS Trees

Description

https://www.luogu.com.cn/problem/CF1495D

Solution

放任务计划里面好久的题目了。本来还以为是什么很困难的高妙题目。

$n,m$ 比较小,所以可以预处理一些东西以后对 $(s,t)$ 分别计算。

如果 $s,t$ 之间超过 $1$ 条最短路则一定无解。否则我们将路径上的点打上标记。

然后其实 $s,t$ 已经像缩成一个点了。我们只需要统计满足条件的父亲个数即可。像这题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include<bits/stdc++.h>
#define int long long
#define ull unsigned long long
#define maxn 505
#define put() putchar('\n')
#define Tp template<typename T>
#define Ts template<typename T,typename... Ar>
using namespace std;
Tp void read(T &x){
int f=1;x=0;char c=getchar();
while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();}
while (c>='0'&&c<='9') {x=x*10+c-'0';c=getchar();}
x*=f;
}
namespace Debug{
Tp void _debug(char* f,T t){cerr<<f<<'='<<t<<endl;}
Ts void _debug(char* f,T x,Ar... y){while(*f!=',') cerr<<*f++;cerr<<'='<<x<<",";_debug(f+1,y...);}
#define gdb(...) _debug((char*)#__VA_ARGS__,__VA_ARGS__)
}using namespace Debug;
#define fi first
#define se second
#define mk make_pair
const int mod=998244353;
int power(int x,int y=mod-2) {
int sum=1;
while (y) {
if (y&1) sum=sum*x%mod;
x=x*x%mod;y>>=1;
}
return sum;
}
int n,m;
int dis[maxn][maxn],cnt[maxn][maxn],ans[maxn][maxn];
vector<int>to[maxn];
queue<int>q;
void bfs(int id) {
int x;
q.push(id);dis[id][id]=0;cnt[id][id]=1;
while (!q.empty()) {
x=q.front();q.pop();
for (auto y:to[x])
if (dis[id][y]>dis[id][x]+1) dis[id][y]=dis[id][x]+1,cnt[id][y]=cnt[id][x],q.push(y);
else if (dis[id][y]==dis[id][x]+1) cnt[id][y]=min(cnt[id][y]+cnt[id][x],2ll);
}
}
void calc(int s,int t) {
int x,res=1;
for (x=1;x<=n;x++) {
if (dis[s][x]+dis[t][x]==dis[s][t]) continue;
int sum=0;
for (auto y:to[x])
if (dis[s][x]==dis[s][y]+1&&dis[t][x]==dis[t][y]+1)
sum++;
res=res*sum%mod;
}
ans[s][t]=ans[t][s]=res;
}
signed main(void){
int i,j,x,y;
memset(dis,0x3f,sizeof(dis));
read(n);read(m);
for (i=1;i<=m;i++) {
read(x),read(y);
to[x].push_back(y);
to[y].push_back(x);
}
for (i=1;i<=n;i++) bfs(i);
for (i=1;i<=n;i++)
for (j=i;j<=n;j++) if (cnt[i][j]==1) {
calc(i,j);
}
for (i=1;i<=n;i++,put()) for (j=1;j<=n;j++) printf("%lld ",ans[i][j]);
return 0;
}