最简单写法Floyd还有最短路算法的介绍见之前的博客:
优先队列做最短路比SPFA更稳定,主要是松弛操作的优化
- 找最小值的(即出队解决)
- 更新最小值(即入队解决)
- 两个for循环O(n),松弛操作优化成O(logn)
- 邻接表优化,变成O(Elogn)
部分套用大师兄的代码风格
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int,int> pii;
const int N = 1e4 + 10;
const LL inf = (LL)1e16;
vector<pii> V[N];
int n, m;
bool vis[N];
LL dis[N];
LL cnt[N][N];
struct Node{
int id;
LL d;
Node(){}
Node(int id, LL d):id(id),d(d){}
bool operator < (const Node &A)const{
return d > A.d;
} //也可用cmp比较两个结构体
};
LL solve(int st){
for(int i=1; i<=n; i++){
vis[i] = 0;
dis[i] = inf;
}
dis[st] = 0;
priority_queue<Node> Q;
Q.push(Node(st, 0));
Node nd;
while(!Q.empty()){
nd = Q.top();
Q.pop();
if(vis[nd.id]) continue;
for(int i=0; i<V[nd.id].size(); i++){ //vector从0开始
int j = V[nd.id][i].first;
int k = V[nd.id][i].second;
if(nd.d + k < dis[j]){
dis[j] = nd.d + k;
Q.push(Node(j, dis[j]));
}
}
}
LL ret ;
for(int i=1; i<=n; i++){
cnt[st][i]=dis[i];
}
}
int main(){
int x, y, z;
scanf("%d", &n); //部分题输入边
for(int i=1; i<=n; i++){
V[i].clear();//如果有多组数据,记得清空
}
//按矩阵输入
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
scanf("%d",&z);
if(z!=0)
V[i].push_back(make_pair(j,z));//有向图只有加一次边
}
}
//scanf("%d %d", &st, &ed);
//while(m--){ //按边输入
// scanf("%d %d %d", &x, &y, &z);
// V[x].push_back(make_pair(y, z));
// V[y].push_back(make_pair(x, z));//无向图,记得一次添加两条边
//}
for(int i=1;i<=n;i++)
solve(i);
cin>>m;
while(m--)
{
scanf("%d %d",&x,&y);
if(cnt[x][y]!=inf)
printf("1\n");
else
printf("0\n");
}
return 0;
}