#include #include #include #include #include #include using namespace std; class edge{ public: int u_; // one end of the edge int v_; // the other end of the edge int w_; // weight of the edge edge(int u, int v, int w):u_(u),v_(v),w_(w){} bool operator<(const edge& rhs) const { return w_>rhs.w_;} friend ostream & operator<<(ostream & out,const edge& e){ out << e.u_ << " " << e.v_; } }; void Tokenize(string line, vector & tokens, string delimiters){ string token = ""; string OneCharString = " "; for (int i=0; i>& G, int& n){ fstream inf; inf.open(file_name); string line; while (getline(inf,line).good()){ vector tokens; Tokenize(line, tokens, " \t"); if (tokens.size()==0) break; if ((n!=0)&&(tokens.size()!=n)) break; n = tokens.size(); vector row; for (int i=0; i< tokens.size(); i++) row.push_back(atoi(tokens[i].c_str())); G.push_back(row); } if (G.size()!=n) cout <<"bad graph file!" << endl; inf.close(); } void DFS(int v, const vector>& G, int n, vector& visited, vector& parent, vector& ret){ visited[v] = true; ret.push_back(v); for (int i=0; i< n; i++){ if ((G[v][i]!=0) && (!visited[i])){ parent[i] = v; DFS(i, G, n, visited, parent, ret); } } } vector get_reverse_path(int u, int v, const vector>& G, const vector& parent){ vector ret; ret.push_back(v); while (v!=u){ v = parent[v]; // to deal with u and v in different connected components if (v==-1) break; ret.push_back(v); } // to deal with u and v in different connected components if (v==-1) return vector(); return ret; } void print_all_components(const vector>& G, int n){ vector output; vector visited; vector parent; for (int i=0; i component; DFS(i, G, n, visited, parent, component); sort(component.begin(), component.end()); cout << "{" ; for (int ctr=0; ctr< component.size()-1; ctr++) cout << component[ctr] << ","; cout << component[component.size()-1] << "}" << endl; } } } void print_path(int u, int v, const vector> & G, int n){ vector component; vector visited; vector parent; for (int i=0; i path = get_reverse_path(u, v, G, parent); for (int i=path.size()-1; i>=0; i--) cout << path[i] << " "; cout << endl; } void Kruskal(const vector>& G, int n){ vector MSF; // Minimum spanning forest int cycle_u = -1, cycle_v = -1; vector component_id; for (int i=0; i Q; for (int i=0; i> G2 = G; G2[cycle_u][cycle_v]=0; G2[cycle_v][cycle_u]=0; cout << "A cycle: "; print_path(cycle_u, cycle_v, G2, n); } cout << "Edges in minimum spanning trees:" << endl; for (auto itr=MSF.begin(); itr!= MSF.end(); itr++) cout << *itr << endl; } int main(int argc, char** argv){ vector> G; int n; readGreaph(argv[1], G, n); print_all_components(G, n); Kruskal(G,n); return 0; }