文章目录
图的表示
邻接矩阵
v
[
i
]
[
j
]
v[i][j]
v[i][j],i和j表示从点i到点j的距离或开销
特点能直观的看到两点之前有没有边
缺点:可能内存开销比较大,尤其是对于那种稀疏图来讲
最短路径问题
Floyd算法
可以在
O
(
V
3
)
O(V^3)
O(V3)时间内求得任意两点的最短路径。
这个方法应用了动态规划思想,在之前动态规划专项中普及过这类问题的思考方式。
在此就直接说结论了,如有问题可以参考之前的背包问题。
首先我们定义
d
p
[
k
]
[
i
]
[
j
]
dp[k][i][j]
dp[k][i][j]为用至多用到前k个点的从点i到点j的最短路。
很典型的,划分为两类子问题,第一类不用点k,第二类我一定用到点k。
转移方程如下:
d
p
[
k
]
[
i
]
[
j
]
=
m
i
n
(
d
p
[
k
−
1
]
[
i
]
[
j
]
,
d
p
[
k
]
[
i
]
[
k
]
+
d
p
[
k
]
[
k
]
[
j
]
)
dp[k][i][j]=min(dp[k-1][i][j],dp[k][i][k]+dp[k][k][j])
dp[k][i][j]=min(dp[k−1][i][j],dp[k][i][k]+dp[k][k][j])
显然三层循环可枚举结果。
有时为了方便可以节约内存可以反复利用
d
p
[
i
]
[
j
]
dp[i][j]
dp[i][j]。
例题POJ 2139
Six Degrees of Cowvin Bacon
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 9280 Accepted: 4370
Description
The cows have been making movies lately, so they are ready to play a variant of the famous game “Six Degrees of Kevin Bacon”.
The game works like this: each cow is considered to be zero degrees of separation (degrees) away from herself. If two distinct cows have been in a movie together, each is considered to be one ‘degree’ away from the other. If a two cows have never worked together but have both worked with a third cow, they are considered to be two ‘degrees’ away from each other (counted as: one degree to the cow they’ve worked with and one more to the other cow). This scales to the general case.
The N (2 <= N <= 300) cows are interested in figuring out which cow has the smallest average degree of separation from all the other cows. excluding herself of course. The cows have made M (1 <= M <= 10000) movies and it is guaranteed that some relationship path exists between every pair of cows.
Input
-
Line 1: Two space-separated integers: N and M
-
Lines 2…M+1: Each input line contains a set of two or more space-separated integers that describes the cows appearing in a single movie. The first integer is the number of cows participating in the described movie, (e.g., Mi); the subsequent Mi integers tell which cows were.
Output -
Line 1: A single integer that is 100 times the shortest mean degree of separation of any of the cows.
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
//flyod
//cost
int v[301][301]={0};
int dp[301][301]={0};
int main(){
int N,M;
cin>>N>>M;
for(int i=0;i<M;i++)
{
int m,last;
cin>>m;
vector<int> vv;
for(int j=0;j<m;j++){
cin>>last;
vv.push_back(last);
}
for(int j=0;j<m;j++){
for(int k=0;k<m;k++)
{
if(k==j) continue;
v[vv[j]][vv[k]]=1;
v[vv[k]][vv[j]]=1;
}
}
}
for(int i=1;i<=N;i++){
for(int j=1;j<=N;j++)
if(v[i][j]!=0 || (i==j))
dp[i][j]=v[i][j];
else
dp[i][j]=INT_MAX/4;
}
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]);
}
int mi=INT_MAX;
for(int i=1;i<=N;i++){
int res=0;
for(int j=1;j<=N;j++)
{
//dp[i][j];
res+=dp[i][j];
}
mi=min(mi,res);
}
cout<<float(mi)/(N-1)<<endl;
return 0;
}