PA2019 Final Floyd-Warshall

Floyd-Warshall

Description

image-20231017210623397

Solution

考虑从小往大枚举起点。

钦定终点大于起点。那么一条最短路径是合法的,当且仅当除了最后一段连续上升的子串,没有连续的 $>s$ 的节点。

比如 1 3 2 4 是合法的,而 2 4 3 1 5 不是。

这样跑出最短路后,建出最短路径的 DAG,然后跑 dp 即可。

如果终点小于起点,当且仅当除了最前面一段连续下降的子串,没有连续的 $<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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define maxn 2005
#define put() putchar('\n')
#define Tp template<typename Ty>
#define Ts template<typename Ty,typename... Ar>
using namespace std;
void read(int &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,Ty t){cerr<<f<<'='<<t<<endl;}
Ts void _debug(char* f,Ty x,Ar... y){while(*f!=',') cerr<<*f++;cerr<<'='<<x<<",";_debug(f+1,y...);}
Tp ostream& operator<<(ostream& os,vector<Ty>& V){os<<"[";for(auto& vv:V) os<<vv<<",";os<<"]";return os;}
#define gdb(...) _debug((char*)#__VA_ARGS__,__VA_ARGS__)
}using namespace Debug;
#define fi first
#define se second
#define mk make_pair
const int mod=1e9+7;
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;
vector<pair<int,int> >to[maxn],pre[maxn];
priority_queue<pair<int,int> >q;
const int inf=1e9;
int dis[maxn],vis[maxn];
void dj(int s) {
int i,x;
for (i=1;i<=n;i++) dis[i]=inf,vis[i]=0;
q.push(mk(0,s));dis[s]=0;
while (!q.empty()) {
x=q.top().se;q.pop();
if (vis[x]) continue;vis[x]=1;
for (auto tmp:to[x]) if (dis[tmp.fi]>dis[x]+tmp.se) {
dis[tmp.fi]=dis[x]+tmp.se;
q.push(mk(-dis[tmp.fi],tmp.fi));
}
}
}
int f[maxn][4];
vector<int>O[maxn];
int in[maxn],ans;
void solve(int s) {
int i,x;
dj(s);
for (i=1;i<=n;i++) O[i].clear(),memset(f[i],0,sizeof(f[i])),in[i]=0;
f[s][0]=1;
for (i=1;i<=n;i++) if (dis[i]<=3e8) {
for (auto tmp:to[i]) if (dis[tmp.fi]==tmp.se+dis[i]) {
O[i].push_back(tmp.fi);
// gdb(i,tmp.fi);
in[tmp.fi]++;
}
}
queue<int>q;
q.push(s);
while (!q.empty()) {
x=q.front();q.pop();
for (auto y:O[x]) {
if (y<s) {
f[y][0]|=f[x][0]|f[x][1];
}
else {
f[y][1]|=f[x][0];
f[y][2]|=f[x][1]|f[x][0];
if (y>x) f[y][2]|=f[x][1]|f[x][2];
}
if (!--in[y]) q.push(y);
}
}
for (i=1;i<=n;i++) if (f[i][0]==0&&f[i][1]==0&&f[i][2]==0&&f[i][3]==0&&dis[i]<inf&&i>s) ans++;//,gdb(s,i);
}
signed main(void){
freopen("1.in","r",stdin);
int i,x,y,z;
read(n);read(m);
for (i=1;i<=m;i++) {
read(x),read(y),read(z);
to[x].push_back(mk(y,z));
pre[y].push_back(mk(x,z));
}
for (i=1;i<=n;i++) solve(i);
for (i=1;i<=n;i++) swap(to[i],pre[i]);
for (i=1;i<=n;i++) solve(i);
printf("%d",ans);
return 0;
}