You are on page 1of 4

1.

#include <bits/stdc++.h>

using namespace std;

int visit[100];

vector <int> g[100];

stack <int> topo;

void dfs(int u) {

visit[u] = 1;

for (auto v : g[u]) {

if (visit[v]==0) dfs(v);

topo.push(u);

int main() {

int m,n;

freopen("jobs.txt","r",stdin);

freopen("jobs.out","w",stdout);

cin >> n >> m;

while (m--) {

int u, v;

cin >> u >> v;

g[u].push_back(v);

for (int i = 1; i <= n; ++i)

if (!visit[i]) dfs(i);
int cnt = 0;

while (!topo.empty()) {

cout<<topo.top()<<" ";

topo.pop();

2.

#include<bits/stdc++.h>

using namespace std;

class DisjointSet {

public:

DisjointSet(int n) {

parent.resize(n);

for (int i = 0; i < n; i++) {

parent[i] = i;

int find(int x) {

if (parent[x] != x) {

parent[x] = find(parent[x]);

return parent[x];

void unionSets(int x, int y) {


int rootX = find(x);

int rootY = find(y);

if (rootX != rootY) {

parent[rootX] = rootY;

private:

vector<int> parent;

};

struct Edge {

int u, v, cost;

};

bool compareEdges(const Edge& a, const Edge& b) {

return a.cost < b.cost;

int main() {

int n, m;

freopen("connection.txt","r",stdin);

freopen("connection.out","w",stdout);

cin>>n>>m;

vector<Edge> edges(m);

for (int i = 0; i < m; i++) {

cin >> edges[i].u >> edges[i].v >> edges[i].cost;

}
sort(edges.begin(), edges.end(), compareEdges);

DisjointSet dsu(n);

int totalCost = 0;

vector<Edge> selectedEdges;

for (const Edge& edge : edges) {

if (dsu.find(edge.u) != dsu.find(edge.v)) {

dsu.unionSets(edge.u, edge.v);

totalCost += edge.cost;

selectedEdges.push_back(edge);

cout << totalCost << endl;

for (const Edge& edge : selectedEdges) {

cout << edge.u << " " << edge.v << " " << edge.cost << endl;

You might also like