Pagini recente » Cod sursa (job #1305876) | Cod sursa (job #2569484) | Cod sursa (job #2046906) | Cod sursa (job #403859) | Cod sursa (job #2425592)
#include <iostream>
#include <fstream>
#include <list>
#include <vector>
#include <queue>
#include <climits>
#include <algorithm>
struct weighted_edge {
int from, dest, weight;
bool operator<(const weighted_edge& other) { return weight < other.weight;}
};
std::istream& operator>>(std::istream& inBuff, weighted_edge& edge) { inBuff >> edge.from >> edge.dest >> edge.weight; edge.from--, edge.dest--; return inBuff; }
void TopologicalSort() {
int N, M;
std::ifstream f("sortaret.in");
std::ofstream g("sortaret.out");
f >> N >> M;
std::list<int> *adj = new std::list<int>[N];
std::vector<int> grade(N);
for(int i = 0; i < M; ++i) {
int X, Y;
f >> X >> Y;
adj[X - 1].push_back(Y - 1);
grade[Y - 1]++;
}
std::queue<int> result;
for(size_t i = 0; i < grade.size(); ++i)
if(grade[i] == 0)
result.push(i);
while(!result.empty()) {
int st = result.front();
g << st + 1 << ' ';
result.pop();
for(int nod : adj[st]) {
grade[nod]--;
if(!grade[nod])
result.push(nod);
}
}
delete[] adj;
}
void BellmanFord() {
int N, M, S = 1;
std::ifstream f("bellmanford.in");
std::ofstream g("bellmanford.out");
f >> N >> M;
std::list<std::pair<int, int>> *adj = new std::list<std::pair<int, int>>[N];
for(int i = 0; i < M; ++i) {
int X, Y, C;
f >> X >> Y >> C;
adj[X - 1].push_back({Y - 1, C});
}
std::vector<int> result(N, INT_MAX);
std::vector<int> relax(N, 0);
std::queue<int> Q;
result[S - 1] = 0;
Q.push(S - 1);
while(!Q.empty()) {
int s = Q.front();
relax[s]++;
if(relax[s] == N) {
g << "Ciclu negativ!";
return;
}
Q.pop();
for(auto nod : adj[s])
if(result[s] + nod.second < result[nod.first]) {
result[nod.first] = result[s] + nod.second;
Q.push(nod.first);
}
}
for(int i = 1; i < N; ++i)
g << result[i] << ' ';
}
int root(int x, std::vector<int> father) {
if(x == father[x])
return x;
else
return father[x] = root(father[x], father);
}
void Kruskal() {
int N, M, TW = 0;
std::ifstream f("kruskal.in");
std::ofstream g("kruskal.out");
f >> N >> M;
std::vector<weighted_edge> edges;
for(int i = 0; i < M; ++i) {
weighted_edge edge;
f >> edge;
edges.push_back(edge);
}
sort(edges.begin(), edges.end());
std::vector<int> father(N);
for(int i = 0; i < N; ++i)
father[i] = i;
std::vector<weighted_edge> result;
for(weighted_edge edge : edges) {
if(result.size() == N)
break;
int rootf = root(edge.from, father);
int rootd = root(edge.dest, father);
if(rootf != rootd) {
result.push_back(edge);
father[rootd] = rootf;
TW += edge.weight;
}
}
g << TW << '\n';
g << result.size() << '\n';
for(weighted_edge edge : result)
g << edge.from + 1 << ' ' << edge.dest + 1 << '\n';
}
int main() {
//TopologicalSort();
//BellmanFord();
Kruskal();
return 0;
}