Pagini recente » Cod sursa (job #3221469) | Cod sursa (job #379754) | Cod sursa (job #583019) | Cod sursa (job #580547) | Cod sursa (job #2425628)
#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, cnt = 0;
std::ifstream f("apm.in");
std::ofstream g("apm.out");
f >> N >> M;
std::vector<weighted_edge> edges(M);
for(int i = 0; i < M; ++i) {
weighted_edge edge;
f >> edge;
edges[i] = edge;
}
std::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(N);
for(weighted_edge edge : edges) {
if(cnt == N - 1)
break;
int rootf = root(edge.from, father);
int rootd = root(edge.dest, father);
if(rootf != rootd) {
result[cnt++] = edge;
father[rootd] = rootf;
TW += edge.weight;
}
}
g << TW << '\n';
g << N - 1 << '\n';
for(weighted_edge edge : result)
g << edge.from + 1 << ' ' << edge.dest + 1 << '\n';
}
int main() {
//TopologicalSort();
//BellmanFord();
Kruskal();
return 0;
}