链接:https://ac.nowcoder.com/acm/contest/878/I
来源:牛客网
题目描述
Give you a graph G of n points, numbered 1-n. We define the Geosetic set of two points as Geodetic(x,y), representing the set of points on all the shortest path from point x to point y.
Each point has a weight wi, we define the sum of the points in Geodetic (x, y) corresponding to wi as U(x,y)
We guarantee that there is no self-loop and there is at most one edge between two points.
For example
Geodetic(2,5)={2,3,4,5}
Geodetic(1,5)={1,3,5}
U(2,5)=6+2+7+4=19
U(1,5)=1+2+4=7
输入描述:
The first line contains two integers n and m (3<=n<=200,1<=m<=n*(n-1)/2)—the number of points and the number of edges. The second line contains n integers, w1, w2, w3,…,wn(1<=wi<=1e6). The next m lines, two integers x and y per line, indicate that there is an undirected edge between x and y with a length of 1. The next line is a integer q(1<=q<=1e5)-the number of questions, the next q lines, two integers x and y per line, indicate a question.
输出描述:
q lines, one integer per line.
示例1
输入
复制
5 6 1 6 2 7 4 1 2 1 3 2 3 2 4 3 5 4 5 3 2 5 5 1 2 4
输出
复制
19 7 13
一个很简单的floyd最短路问题,当时想到了没写出来。
两个点之间会有多条最短路径,但是没关系,两点之间最短路长度是固定的,所以用floyd算出任意两点的长度,然后枚举第三点,如果这个点在最短路上,也就是d[u][v]==d[u][i]+d[i][v],那么就可以将这个点i的权值加入答案。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
#include <queue>
using namespace std;
const int maxn=200+10;
int dp[maxn][maxn];
const int INF=0x3f3f3f3f;
int n,m;
//int ans[maxn][maxn];
int val[maxn];
void init(){
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
dp[i][j]=INF;
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
dp[i][j]=INF;
}
}
}
void floyd(){
for(int k=1;k<=n;k++){
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
dp[i][j]=min(dp[i][j],dp[i][k]+dp[k][j]);
dp[j][i]=dp[i][j];
}
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
dp[j][i]=dp[i][j];
}
}
}
int solve(int u,int v){
int ans=0;
ans+=val[u];
ans+=val[v];
for(int i=1;i<=n;i++){
if(i==u||i==v)continue;
if(dp[u][v]==dp[u][i]+dp[i][v]){
ans+=val[i];
//printf("index: %d\n",i);
}
}
return ans;
}
int main(){
while(scanf("%d%d",&n,&m)!=EOF){
for(int i=1;i<=n;i++){
scanf("%d",&val[i]);
}
init();
for(int i=1;i<=m;i++){
int u,v;
scanf("%d%d",&u,&v);
dp[u][v]=1;
dp[v][u]=1;
}
floyd();
int q;
scanf("%d",&q);
while(q--){
int u,v;
scanf("%d%d",&u,&v);
printf("%d\n",solve(u,v));
}
}
return 0;
}