跳到正文

题解

题解:P4610 [COI 2012] KAMPANJA

_lbw_约 3 分钟
原文

这是 2026年4月10日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年4月10日
收录
2026年4月10日
更新
2026年11月11日
篇幅
约 3 分钟
题目
P4610

版本

  1. v2当前
  2. v1

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

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

假设 1→21\to 2 的路径为 pi(i∈[1,k])p_i(i\in [1,k]),那么 2→12\to 1 经过的是若干段 xi≤yix_i\leq y_i,从 yty_t 沿外部走到 xt+1x_{t+1},然后沿 1→21\to 2 的路径 xt→ytx_t\to y_t。

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

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

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

C++
#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;
}