Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- struct Edge
- {
- int source, dest, cost;
- };
- Edge edge[100];
- int par[100];
- int g[100][100];
- bool compare(const Edge &x, const Edge &y)
- {
- return x.cost<y.cost;
- }
- int find (int v)
- {
- if (par[v]==-1) return v;
- par[v] = find(par[v]);
- return par[v];
- }
- void merge (int v1, int v2)
- {
- par[v1] = v2;
- return;
- }
- void Kruskal (int v, int e)
- {
- int cnt=0, pos=1, source, dest, cost;
- Edge now;
- while(cnt<v-1)
- {
- if (pos>e) return;
- now = edge[pos++];
- source = now.source;
- dest = now.dest;
- cost=now.cost;
- int v1 = find(source);
- int v2 = find(dest);
- if(v1!=v2)
- {
- g[source][dest] = cost;
- merge(v1, v2);
- cnt++;
- }
- }
- return;
- }
- int main()
- {
- int v,e;
- scanf("%d%d", &v, &e);
- int i, j;
- int source, dest, cost;
- for(i=0; i<=v; i++)
- {
- par[i]=-1;
- }
- for(i=0; i<e; i++)
- {
- scanf("%d%d%d", &source, &dest, &cost);
- edge[i].source = source;
- edge[i].dest = dest;
- edge[i].cost = cost;
- }
- memset(g, -1, sizeof(g));
- sort (edge, edge+e, compare);
- Kruskal(v, e);
- for(i=0; i<=v; i++)
- {
- for(j=0; j<=v; j++)
- {
- if(g[i][j]!=-1)
- {
- printf("Vertex %d and %d, cost %d\n", i, j, g[i][j]);
- }
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement