WuKong
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1804 Accepted Submission(s): 672
One day, Wukong left his home - Mountain of Flower and Fruit, to the Dragon King’s party, at the same time, Tang Monk left Baima Temple to the Lingyin Temple to deliver a lecture. They are both busy, so they will choose the shortest path. However, there may be several different shortest paths between two places. Now the Buddha wants them to encounter on the road. To increase the possibility of their meeting, the Buddha wants to arrange the two routes to make their common places as many as possible. Of course, the two routines should still be the shortest paths.
Unfortunately, the Buddha is not good at algorithm, so he ask you for help.
The input are ended with N=M=0, which should not be processed.
6 6 1 2 1 2 3 1 3 4 1 4 5 1 1 5 2 4 6 3 1 6 2 4 0 0
3 Hint: One possible arrangement is (1-2-3-4-6) for Wukong and (2-3-4) for Tang Monk. The number of common points are 3.
题目大意:
给你一张无向图和两条路径的起点和终点,求都以最短路走时的最长公共点个数
题目思路:
我们很容易想到的是,因为都是走最短路,所以公共的点一定是连续的,既然是连续的
我们不妨用dp[i][j]来表示从i到j的最短路经过的点有多少个,而处理这个我们可以用floyd
来处理这个,我们知道floyd跟新k点的时候是mp[i][j]=mp[i][k]+mp[k][j],所以就相当于把ij拆
开接到k上,所以我们很好想到dp[i][j]=dp[i][k]+dp[k][j]-1,因为k点重复了一次所以要减去1
处理多条路径时我们只需dp[i][j]= max(dp[i][j],dp[i][k]+dp[k][j]-1); 所以我们只需枚举所有的ij
的组合,而要使i->j是属于两条路径的我们可以想到当mp[s][i]+mp[i][j]+mp[j][e]==mp[s][e]时
可知ij是属于se的,因为这都是最短路径
AC代码:
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int maxn = 5e2+10;
const int inf = 1e9;
int mp[maxn][maxn],dp[maxn][maxn];
int n,m,s0,e0,s1,e1;
void floyd(){
for(int k=1;k<=n;k++)
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++){
if(mp[i][j]>mp[i][k]+mp[k][j]){
mp[i][j]=mp[i][k]+mp[k][j];
dp[i][j]=dp[i][k]+dp[k][j]-1;
}else if(mp[i][j]==mp[i][k]+mp[k][j]&&dp[i][j]<dp[i][k]+dp[k][j]){
dp[i][j]=dp[i][k]+dp[k][j]-1;
}
}
}
void sove(){
int ans = 0;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++){
if(mp[s0][i]+mp[i][j]+mp[j][e0]==mp[s0][e0]&&mp[s1][i]+mp[i][j]+mp[j][e1]==mp[s1][e1])
ans=max(dp[i][j],ans);
}
printf("%d\n",ans);
}
int main()
{
while(scanf("%d%d",&n,&m),n+m){
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
if(i!=j)mp[i][j]=inf,dp[i][j]=2;
else mp[i][j]=0,dp[j][j]=1;
while(m--){
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
mp[u][v]=mp[v][u]=min(mp[u][v],w);
}
scanf("%d%d%d%d",&s0,&e0,&s1,&e1);
floyd();
sove();
}
return 0;
}