图结构练习——最短路径
题目
坑点
题目输入的时候会有重边。比如说:
2 2
1 2 1
1 2 2
答案应该是1。
题解
就是jd最短路模板题,不多说
代码1:临界矩阵
使用临界矩阵,注意判断重边
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define PII pair<int, int>
#define x first
#define y second
const int maxn = 1e6 + 10;
const int INF = 0x3f3f3f3f;
const ll M = 11092019;
const int N = 100010;
int g[110][110];
int n, m;
int vis[110];
int dis[110];
void dj()
{
priority_queue<PII, vector<PII>, greater<PII>> q;
q.push({0, 1});
dis[1] = 0;
while (q.size())
{
PII k = q.top();
q.pop();
if (vis[k.second])
continue;
vis[k.second] = 1;
for (int i = 1; i <= n; i++)
{
if (g[k.second][i])
{
int dist = k.first + g[k.second][i];
if (dis[i] > dist)
{
dis[i] = dist;
q.push({dis[i], i});
//cout<<dis[i]<<" "<<i<<endl;
}
}
}
}
}
int main()
{
while (cin >> n >> m)
{
memset(g, 0, sizeof g);
memset(dis, 0x3f, sizeof dis);
memset(vis, 0, sizeof vis);
for (int i = 0; i < m; i++)
{
int a, b, c;
cin >> a >> b >> c;
if (!g[a][b])//判断重边
g[a][b] = g[b][a] = c;
else
{
g[a][b] = g[b][a] = min(c, g[a][b]);
}
}
dj();
cout << dis[n] << endl;
}
return 0;
}
代码2:邻接表
邻接表就不需要判断重边,因为两个边都会输入
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define PII pair<int, int>
#define x first
#define y second
const int maxn = 1e6 + 10;
const int INF = 0x3f3f3f3f;
const ll M = 11092019;
const int N = 100010;
vector<PII> g[110];
int n, m;
int vis[110];
int dis[110];
void dj()
{
priority_queue<PII, vector<PII>, greater<PII>> q;
q.push({0, 1});
dis[1] = 0;
while (q.size())
{
PII k = q.top();
q.pop();
if (vis[k.second])
continue;
vis[k.second] = 1;
for(PII t: g[k.second]){
int dist=t.first+k.first;
int ver=t.second;
if(dist<dis[ver]){
dis[ver]=dist;
// cout<< ver<< " "<<dis[ver]<<endl;
q.push({dis[ver],ver});
}
}
}
}
int main()
{
while (cin >> n >> m)
{
for(int i=0;i<n;i++){
g->clear();
}
memset(g, 0, sizeof g);
memset(dis, 0x3f, sizeof dis);
memset(vis, 0, sizeof vis);
for (int i = 0; i < m; i++)
{
int a, b, c;
cin >> a >> b >> c;
g[a].push_back({c,b});
g[b].push_back({c,a});
}
dj();
cout << dis[n] << endl;
}
return 0;
}