题解:P4610 [COI 2012] KAMPANJA

· · 题解

复杂度 \mathcal{O}(nm\log n) 做法。

观察答案,可以看做 1\to 2,2\to 1 的长度减去重复的长度,所以考虑重复的点长成什么样。

假设 1\to 2 的路径为 p_i(i\in [1,k]),那么 2\to 1 经过的是若干段 x_i\leq y_i,从 y_t 沿外部走到 x_{t+1},然后沿 1\to 2 的路径 x_t\to y_t。

那么可以从 {1,1} 开始 dp,转移分别为两个点走一步和 x_t\to y_t 这种情况,这种情况相当于交换两个点。

转移数量是 nm,总复杂度 \mathcal{O}(nm\log n)。

代码用了 floyd,可以换成 BFS。

#undef ll
#include "assert.h"
mt19937_64 rnd(her1);
#include "functional"
using i64 = long long;
const int maxn = 1e2+5;
i64 n,m,f[maxn][maxn],dis[maxn][maxn];
vector<i64>g1[maxn],g2[maxn];
bool to[maxn][maxn];
int main(){ 
    // freopen("1.in","r",stdin);
    // freopen("1.out","w",stdout);

    n=read();m=read();
    F(i,1,n)F(j,1,n)if(i^j)dis[i][j]=1e9;
    F(i,1,m){
        i64 u=read(),v=read();
        g1[u].push_back(v);
        g2[v].push_back(u);
        to[u][v]=1;
        dis[u][v]=1;
    }
    F(k,1,n)F(i,1,n)F(j,1,n)
        dis[i][j]=min(dis[i][k]+dis[k][j],dis[i][j]);

    priority_queue<array<i64,3> >qwq;
    F(i,1,n)F(j,1,n)f[i][j]=1e9;

    qwq.push({-(f[1][1]=1),1,1});
    while(!qwq.empty()){
        auto[w,x,y]=qwq.top();qwq.pop();
        if(f[x][y]!=-w)continue;
        if(x!=y){
            if(f[x][y]+dis[x][y]-1<f[y][x])
                qwq.push({-(f[y][x]=f[x][y]+dis[x][y]-1),y,x});
        }
        for(i64 i:g1[x])if(f[x][y]+1<f[i][y])
            qwq.push({-(f[i][y]=f[x][y]+1),i,y});
        for(i64 i:g2[y])if(f[x][y]+1<f[x][i])
            qwq.push({-(f[x][i]=f[x][y]+1),x,i});
        for(i64 i:g1[x])if(to[i][y]&&f[x][y]+1<f[i][i])
            qwq.push({-(f[i][i]=f[x][y]+1),i,i});
    }
    cout<<f[2][2];

    return 0;
}