题解:P6030 [SDOI2012] 走迷宫
AnotherDream · · 题解
题意简述
一个有向图,问从
思路
先考虑期望为
如果说无法到达,根据题意,期望步数显然是
如果说
现在它就一定有解了。
看到这个期望想到 DP,由于期望一般倒推,设
对于
现在
时间复杂度
:::success[代码]
#include <bits/stdc++.h>
using namespace std;
#define debug cerr<<"The code runs successfully.\n";
#define endl '\n'
#define TRACE 1
#define tcout TRACE && cout
#define fst ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define int long long
#define fir first
#define sec second
const int P = 998244353;
const int Base = 33331;
#ifdef int
const int INF = 0x3f3f3f3f3f3f3f3f;
#else
const int INF = 0x3f3f3f3f;
#endif
const int N = 1e4 + 10, M = 101 + 10;
const double EPS = 1e-10;
int n,m,st,ed,dfn[N],low[N],id,in[N],cnt,num[N],vis[N],du[N],siz[N],bh[N],viss[N];
vector<int> scc[N];
stack<int> stk;
vector<int> g[N],G[N];
double a[M][M],dp[N];
void tarjan(int u) {//缩点
dfn[u]=low[u]=++id;
stk.push(u);
in[u]=1;
for(int v:g[u]) {
if(!dfn[v]) {
tarjan(v);
low[u]=min(low[u],low[v]);
}
else if(in[v]) low[u]=min(low[u],dfn[v]);
}
if(low[u]==dfn[u]) {
cnt++;
num[u]=cnt;
siz[cnt]=1;
scc[cnt].push_back(u);
while(stk.top()!=u) {
int x=stk.top();
in[x]=0,num[x]=cnt;
scc[cnt].push_back(x);
stk.pop();
siz[cnt]++;
}
stk.pop();
in[u]=0;
}
}
inline int gauss(int n) {//高消
int cnt=1;
for(int i=1;i<=n;i++) {
int pt=cnt;
for(int j=cnt+1;j<=n;j++) if(fabs(a[j][i])>fabs(a[pt][i])) pt=j;
swap(a[cnt],a[pt]);
if(fabs(a[cnt][i])<EPS) continue;
for(int j=n+1;j>=i;j--) a[cnt][j]/=a[cnt][i];
for(int j=1;j<=n;j++) {
if(j==cnt) continue;
for(int k=n+1;k>=i;k--) a[j][k]-=a[j][i]*a[cnt][k];
}
cnt++;
}
int key=0;
for(int i=1;i<=n;i++) {
bool flg=1;
for(int j=1;j<=n;j++) {
if(fabs(a[i][j])>=EPS) {
flg=0;
break;
}
}
if(flg) {
if(fabs(a[i][n+1]>=EPS)) key=-1;
else if(key!=-1) key=1;
}
}
return key;
}
bool dfs(int u) {
vis[u]=1;
if(u==ed) return 1;//已经到了
if(g[u].empty()) return 0;//无路可走
for(int v:g[u]) if(!vis[v]) if(!dfs(v)) return 0;//有一个到不了就是inf
return 1;//全部能到
}
bool dfs1(int u) {//同理
viss[u]=1;
if(u==num[ed]) return 1;
if(G[u].empty()) return 0;
for(int v:G[u]) if(!viss[v]) if(!dfs1(v)) return 0;
return 1;
}
signed main() {
fst;
cin>>n>>m>>st>>ed;
for(int i=1;i<=m;i++) {
int u,v;
cin>>u>>v;
g[u].push_back(v);
du[u]++;
}
for(int i=1;i<=n;i++) if(!dfn[i]) tarjan(i);
for(int i=1;i<=n;i++) {
int u=num[i];
for(int v:g[i]) {
v=num[v];
if(u!=v) G[u].push_back(v);
}
}
if(!dfs(st)||!dfs1(num[st])) {//无解
cout<<"INF"<<endl;
return 0;
}
for(int i=1;i<=cnt;i++) {
if(!viss[i]) continue;
int tmp=0;
for(int x:scc[i]) bh[x]=++tmp;//维护编号
for(int u:scc[i]) {
int x=bh[u];
//列方程
if(u==ed) a[x][x]=1;
else {
a[x][x]=du[u];
a[x][siz[i]+1]=du[u];
for(int v:g[u]) {
int vv=bh[v];
if(vv!=0) {
a[x][vv]-=1;
}
else {
a[x][siz[i]+1]+=dp[v];
}
}
}
}
gauss(tmp);
int ccc=0;
//转移到dp
for(int x:scc[i]) {
ccc++;
dp[x]=a[ccc][siz[i]+1];
}
//情况
for(int x:scc[i]) bh[x]=0;
for(int x=1;x<=tmp;x++) {
for(int y=1;y<=tmp+1;y++) {
a[x][y]=0;
}
}
}
cout<<fixed<<setprecision(3)<<dp[st]<<endl;
return 0;
}
:::