关于邻接矩阵
反正那两种都写了,这也写一下吧
邻接矩阵,最为朴实无华的存图方法,其基本思路为:
如果u,v之间存在长度为w的有向边,那么矩阵edge[u][v]=w
那么加边就可以轻松实现了:
void add(int u, int v, int w)
{
edge[u][v] = w;
}
那么遍历点的出边也就很容易了:
for(int i = 1;i <= n;++i)
{
if(edge[u][i] == INF) continue;
}
当然,你还需要初始化矩阵:
memset(edge, 0x7f, sizeof edge);
for(int i = 1;i <= n;++i)
edge[i][i] = 0;
没想到吧邻接矩阵也有dij:
#include <iostream>
#include <queue>
#include <utility>
#include <functional>
#include <cstring>
using namespace std;
int edge[2001][2001], n, m, s, u, v, w, dis[2001], vis[2001];
priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > q;
void add(int u, int v, int w)
{
edge[u][v] = w;
}
int main()
{
cin >> n >> m >> s;
memset(edge, 0x7f, sizeof edge);
for(int i = 1;i <= n;++i)
edge[i][i] = 0;
for(int i = 0;i < m;++i)
cin >> u >> v >> w, add(u, v, w);
for(int i = 1;i <= n;++i)
dis[i] = 0x7f7f7f7f;
dis[s] = 0;q.push(make_pair(0, s));
while(!q.empty())
{
int u = q.top().second;q.pop();
if(vis[u]) continue;
vis[u] = 1;
for(int i = 1;i <= n;++i)
{
if(edge[u][i] == 0x7f7f7f7f) continue;
if(dis[i] > dis[u] + edge[u][i])
{
dis[i] = dis[u] + edge[u][i];
q.push(make_pair(dis[i], i));
}
}
}
for(int i = 1;i <= n;++i)
cout << dis[i] << " ";
return 0;
}