算法训练营|图论第8天 拓扑排序 dijkstra
题目:
拓扑排序
题目链接:
117. 软件构建 (kamacoder.com)
代码:
#include<bits/stdc++.h>
#include<unordered_map>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
vector<int>inDegree(n, 0);
unordered_map<int, vector<int>>myMap;
vector<int>result;
for (int i = 0; i < m; i++) {
int s, t;
cin >> s >> t;
inDegree[t]++;
myMap[s].push_back(t);
}
queue<int>que;
for (int i = 0; i < n; i++) {
if (inDegree[i] == 0) {
que.push(i);
}
}
while (!que.empty()) {
int cur = que.front();
que.pop();
result.push_back(cur);
vector<int>files = myMap[cur];
if (files.size() != 0) {
for (int i = 0; i < files.size(); i++) {
inDegree[files[i]]--;
if (inDegree[files[i]] == 0) {
que.push(files[i]);
}
}
}
}
if (result.size() == n) {
for (int i = 0; i < n - 1; i++) {
cout << result[i] << ' ';
}
cout << result[n - 1] << endl;
}
else {
cout << -1 << endl;
}
}
题目:
dijkstra
题目链接:
47. 参加科学大会(第六期模拟笔试) (kamacoder.com)
代码:
#include<bits/stdc++.h>
using namespace std;
int main() {
int n, m, s, e, v;
cin >> n >> m;
vector<vector<int>>grid(n + 1, vector<int>(n + 1, INT_MAX));
for (int i = 0; i < m; i++) {
cin >> s >> e >> v;
grid[s][e] = v;
}
vector<int>minDist(n + 1, INT_MAX);
vector<bool>visited(n + 1, false);
int start = 1;
int end = n;
minDist[start] = 0;
for (int i = 1; i <= n; i++) {
int minVal = INT_MAX;
int cur = 1;
for (int v = 1; v <= n; v++) {
if (!visited[v] && minDist[v] < minVal) {
cur = v;
minVal = minDist[v];
}
visited[cur] = true;
for (int v = 1; v <= n; v++) {
if (!visited[v] && grid[cur][v] != INT_MAX && minDist[cur] + grid[cur][v] < minDist[v]) {
minDist[v] = minDist[cur] + grid[cur][v];
}
}
}
}
if (minDist[end] == INT_MAX) cout << -1 << endl;
else {
cout << minDist[end] << endl;
}
}