12345678910111213141516171819
6 9 // 6= nr of vertices; 9=nr of edges 1 2 2 // edge 1 edge 2 cost 1 3 4 // edge 1 edge 3 cost 2 3 1 // edge 2 edge 3 cost 2 4 4 2 5 2 3 5 3 4 6 2 5 4 3 5 6 2 5 7 // 5= nr of vertices; 7=nr of edges 1 2 10 1 4 30 1 5 100 2 3 50 3 5 10 4 3 20 4 5 60
1234567891011121314151617181920212223242526272829303132
#include <iostream> #include <fstream> using namespace std; int main() { ifstream infile("data.txt"); int n,m; int a,b,c; int cost[100][100]; for(int i=0;i<n;++i) { for(int j=0;j<n;++j) { cost[i][j]=0; } } if (infile>>n>>m) { while (infile>>a>>b>>c) { for(int i=0;i<n;++i) { for(int j=0;j<n;++j) { cost[a-1][b-1]=c; } } } } for(int i=0;i<n;++i) { for(int j=0;j<n;++j) { cout<<cost[i][j]<<" "; } cout<<endl; } infile.close(); }
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
#include <iostream> #include <iomanip> #include <sstream> #include <vector> using namespace std; class Graph { int numVert; vector< vector<int> > adj; public: Graph( istream &in ); void write( ostream &out ); }; Graph::Graph( istream &in ) { int nedge, a, b, cost; in >> numVert >> nedge; adj = vector< vector<int> >( numVert, vector<int>( numVert, 0 ) ); for ( int i = 0; i < nedge; i++ ) { in >> a >> b >> cost; adj[a-1][b-1] = cost; // adj[b-1][a-1] = cost; // need this as well if graph is undirected } } void Graph::write( ostream &out ) { for ( int i = 0; i < numVert; i++ ) { for ( int j = 0; j < numVert; j++ ) out << setw( 2 ) << adj[i][j] << ' '; out << '\n'; } } //====================================================================== int main() { istringstream in( "6 9 \n" "1 2 2 \n" "1 3 4 \n" "2 3 1 \n" "2 4 4 \n" "2 5 2 \n" "3 5 3 \n" "4 6 2 \n" "5 4 3 \n" "5 6 2 \n" " \n" "5 7 \n" "1 2 10 \n" "1 4 30 \n" "1 5 100\n" "2 3 50 \n" "3 5 10 \n" "4 3 20 \n" "4 5 60 \n" ); Graph G(in), H(in); G.write( cout ); cout << "\n\n"; H.write( cout ); }
0 2 4 0 0 0 0 0 1 4 2 0 0 0 0 0 3 0 0 0 0 0 0 2 0 0 0 3 0 2 0 0 0 0 0 0 0 10 0 30 100 0 0 50 0 0 0 0 0 0 10 0 0 20 0 60 0 0 0 0 0