我有一个代码,可以找到最小的生成树权重。边被声明为int,但我需要将它们作为字符串。如何修改才能正常工作? 如果将vector修改为字符串,则会在编译器中看到很多错误。请帮助我完成这段代码,我是编程新手。
#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> iPair;
struct Graph
{
int Edges, Connections;
vector< pair<int, iPair> > edges;
Graph(int Edges, int Connections)
{
this->Edges = Edges;
this->Connections = Connections;
}
void addEdge(int u, int v, int w)
{
edges.push_back({w, {u, v}});
}
int kruskalMST();
};
struct DisjointSets
{
int *parent, *rnk;
int n;
DisjointSets(int n)
{
// Allocate memory
this->n = n;
parent = new int[n+1];
rnk = new int[n+1];
// Initially, all vertices are in
// different sets and have rank 0.
for (int i = 0; i <= n; i++)
{
rnk[i] = 0;
//every element is parent of itself
parent[i] = i;
}
}
// Find the parent of a node 'u'
// Path Compression
int find(int u)
{
/* Make the parent of the nodes in the path
from u--> parent[u] point to parent[u] */
if (u != parent[u])
parent[u] = find(parent[u]);
return parent[u];
}
// Union by rank
void merge(int x, int y)
{
x = find(x), y = find(y);
/* Make tree with smaller height
a subtree of the other tree */
if (rnk[x] > rnk[y])
parent[y] = x;
else // If rnk[x] <= rnk[y]
parent[x] = y;
if (rnk[x] == rnk[y])
rnk[y]++;
}
};
/* Functions returns weight of the MST*/
int Graph::kruskalMST()
{
int mst_wt = 0; // Initialize result
// Sort edges in increasing order on basis of cost
sort(edges.begin(), edges.end());
// Create disjoint sets
DisjointSets ds(Edges);
// Iterate through all sorted edges
vector< pair<int, iPair> >::iterator it;
for (it=edges.begin(); it!=edges.end(); it++)
{
int u = it->second.first;
int v = it->second.second;
int set_u = ds.find(u);
int set_v = ds.find(v);
if (set_u != set_v)
{
cout << u << " - " << v << " = " << it->first << endl;
mst_wt += it->first;
ds.merge(set_u, set_v);
}
}
return mst_wt;
}
// Driver program to test above functions
int main()
{
int from,to,weight,i;
/* Let us create above shown weighted
and unidrected graph */
int Edges, Connections;
cout<<"How many edges?:"; cin>>Edges;
cout<<"How many connections?:"; cin>>Connections;
Graph g(Edges, Connections);
system("cls");
// making above shown graph
for(i=0;i<Connections;i++){
cout<<endl;
cout<<"From "; cin>>from;
cout<<"To "; cin>>to;
cout<<"Weight "; cin>>weight;
g.addEdge(from,to,weight);
system("cls");
}
cout << "Edges of MST are \n";
int mst_wt = g.kruskalMST();
cout << "\nWeight of MST is " << mst_wt;
return 0;
}
Example of 9 edges and 14 connections. Minimal Weight = 37.
From To Weight
0 1 4
0 7 8
1 2 8
1 7 11
2 3 7
2 8 2
2 5 4
3 4 9
3 5 14
4 5 10
5 6 2
6 7 1
6 8 6
7 8 7
Min. Weight = 37
您可以输入您的值作为输入。