Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.
In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction s to work located near junction t. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease.
You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between s and t won't decrease.
The firt line of the input contains integers n, m, s and t (2 ≤ n ≤ 1000, 1 ≤ m ≤ 1000, 1 ≤ s, t ≤ n, s ≠ t) — the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The i-th of the following m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi), meaning that this road connects junctions ui and vi directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.
Print one integer — the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions s and t.
5 4 1 5 1 2 2 3 3 4 4 5
0
5 4 3 5 1 2 2 3 3 4 4 5
5
5 6 1 5 1 2 1 3 1 4 4 5 3 5 2 5
3
题意:
n个城市之间一共有m条路,求最多还能修几条路使得s到t的最短路径不变
思路:
可以直接枚举任意的两条边,只要满足以下两个条件则认为可以修一条路
1. s->i + i -> j + j->t >= s->t
2. s->j + j-> i + i->t >= s->t
#include<bits/stdc++.h>
#define Inf 0x3f3f3f3f
using namespace std;
const int N =1005;
int ds[N],dt[N],vis[N];
vector<int>G[N];
void Dijkstra(int s,int dis[],int n){
memset(vis,0,sizeof(vis));
//memset(dis,Inf,sizeof(dis)); 不能直接初始化
for(int i=0;i<=n;i++)
dis[i]=Inf;
dis[s]=0;
for(int k=0;k<n;k++){
int mint=Inf,u=0;
for(int i=1;i<=n;i++){
if(!vis[i]&&dis[i]<mint){
mint=dis[i];
u=i;
}
}
vis[u]=1;
for(int i=0;i<G[u].size();i++){
int v=G[u][i];
if(dis[v]>dis[u]+1)
dis[v]=dis[u]+1;
}
}
}
int main(){
int n,m,s,t;
cin>>n>>m>>s>>t;
for(int i=0;i<m;i++){
int a,b;
cin>>a>>b;
G[a].push_back(b);
G[b].push_back(a);
}
Dijkstra(s,ds,n);
Dijkstra(t,dt,n);
int dis=ds[t];
int ans=0;
for(int i=1;i<=n;i++){
for(int j=i+1;j<=n;j++)
if(ds[i]+dt[j]+1>=dis&&ds[j]+dt[i]+1>=dis)
ans++;
}
cout<<ans-m<<endl;
return 0;
}
本文探讨了一个包含多个城市的网络中如何新增道路以确保特定两点间最短路径不缩短的问题。通过枚举所有可能的新道路组合,并利用Dijkstra算法计算最短路径,找出符合条件的新道路方案。
179

被折叠的 条评论
为什么被折叠?



