diff --git a/graph/c++/dijkstra.cpp b/graph/c++/dijkstra.cpp new file mode 100644 index 0000000..3fc18ff --- /dev/null +++ b/graph/c++/dijkstra.cpp @@ -0,0 +1,38 @@ +#include +#include +using namespace std; + +#define fst first +#define snd second +#define pb(a) push_back(a) +#define mp(a, b) make_pair(a, b) +typedef long long ll; + +const int N = 1e5 + 5; +int v, y, cost, best[N]; +vector> graph[N]; + +void dijkstra(int x) { + memset(best, -1, sizeof best); + priority_queue> queue; + best[x] = 0; // First node. + queue.push({x, -best[x]}); // Now it's {x, 0}. + + while(queue.size()){ // While it's not empty. + y = queue.top().fst; // The node we're now. + cost = -queue.top().snd; // The cost to that node. + queue.pop(); // We don't need that node anymore. + + if(cost > best[y]) continue; + for(int i = 0; i < graph[x].size(); i++){ // For every neighbour of x... + v = graph[x][i].fst; // Get the node. + cost = graph[x][i].snd; // Get it's cost. + + // If it's unvisited, or we found a better path... + if(best[v] < 0 or best[y] + cost < best[v]){ + best[v] = best[y] + cost; // Change the cost. + queue.push(mp(v, -best[v])); // Push that node to the queue to visit it's neighbours. + } + } + } +} \ No newline at end of file diff --git a/graph/c++/kruskal.cpp b/graph/c++/kruskal.cpp new file mode 100755 index 0000000..b6c9ad3 --- /dev/null +++ b/graph/c++/kruskal.cpp @@ -0,0 +1,54 @@ +#include +using namespace std; +#define fst first +#define snd second +#define pb(a) push_back(a) +#define mp(a, b) make_pair(a, b) +#define ll long long +const int N = 1000; +vector>> g; // Graph (cost, (x, y)) +ll n, m, a, b, c, mst_weight, mst_vertex, mst_edges, ancestors[N]; + +void set_fathers(){ + for(ll i = 0; i < N; i++){ + ancestors[i] = i; + } +} + +ll father(ll x){ + if(ancestors[x] == x) return x; + else return father(ancestors[x]); +} + +void unite(ll a, ll b){ + ll father_a = father(a); + ll father_b = father(b); + ancestors[father_a] = father_b; +} + +void kruskal(){ + set_fathers(); + sort(g.begin(), g.end()); + + while(mst_vertex < n - 1 or mst_edges < m){ + a = g[mst_edges].snd.fst; + b = g[mst_edges].snd.snd; + c = g[mst_edges].fst; + if(father(a) != father(b)){ + unite(a, b); + mst_weight += c; + mst_vertex++; + } + mst_edges++; + } +} + +int main(){ + cin >> n >> m; + for(ll i = 0; i < m; i++){ + cin >> a >> b >> c; + g.pb(mp(c, mp(a,b))); + } + kruskal(); + return 0; +}