圖的表示
鄰接矩陣
,i和j表示從點i到點j的距離或開銷
特點能直觀的看到兩點之前有沒有邊
缺點:可能內存開銷比較大,尤其是對於那種稀疏圖來講
最短路徑問題
Floyd算法
可以在時間內求得任意兩點的最短路徑。
這個方法應用了動態規劃思想,在之前動態規劃專項中普及過這類問題的思考方式。
在此就直接說結論了,如有問題可以參考之前的揹包問題。
首先我們定義爲用至多用到前k個點的從點i到點j的最短路。
很典型的,劃分爲兩類子問題,第一類不用點k,第二類我一定用到點k。
轉移方程如下:
顯然三層循環可枚舉結果。
有時爲了方便可以節約內存可以反覆利用。
例題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;
}