SlideShare uma empresa Scribd logo
1 de 9
Computer Science Assignment Help
For any help regarding Computer Assignment Help
visit: programminghomeworkhelp.com
Email- support@programminghomeworkhelp.com or call us at-+1 678 648 4277
programminghomeworkhelp.com
Problem 1:
The C++ standard template library provides us with a large number of containers and data structures that we can go ahead and use in our programs. We’ll be learning
how to use a priority queue, which is available in the <queue> header.
The problem we can solve using a priority queue is that of computing a minimum spanning tree. Given a fully connected undirected graph where each edge has a weight,
wewould like to find the set of edges with the least total sum of weights. This may sound abstract; so here’sa concrete scenario:
You’re a civil engineer and you’retrying to figure out the best way to arrange for internet accessin your small island nation of C-Land. There areN (3 ≤ N ≤ 250, 000) towns on
yourisland connectedbyM (N ≤ M ≤ 250, 000) variousroadsand youcanwalk betweenany two townsonthe island bytraversing somesequenceof roads.
However, you’vegot a limited budget and have determined that the cheapest way to arrange for internet access is to build somefiber-optic cables along existing roadways. You have a
list of the costsof laying fiber-optic cable down along any particular road, and want to figure out how much money you’ll need to successfullycomplete the project–meaning that, at
the end, every town will be connected along somesequence of fiber-optic cables.
Luckily, you’re also C-Land’s resident computer scientist, and you remember hearing about Prim’
s algorithm in one of your old programming classes. This algorithm is exactly the
solution to yourproblem, but it requires apriorityqueue...and ta-da! Here’
sthe C++ standard template libraryto the rescue.
If this scenario is still not totally clear, look at the sample input description on the next page. Our input data describing the graph will be arranged as a list of edges (roads
and their fiber-optic cost) and for our program we’ll covert that to an adjacency list: for every node in the graph (town in the country), we’ll have a list of the nodes
(towns) it’sconnected to and the weight (cost of building fiber-optic cable along).
adj[0]→ (1,1.0) (3,3.0)
adj[1]→ (0, 1.0) (2, 6.0) (3, 5.0) (4, 1.0)
. .
This data structure might be a pain to allocate and keep track of everything in C. The C++ STL will simplify things. First, our adjacency list can be represented as a list
of C++ vectors, one for each node. To further simplify and abstract things, we’ve created a wrapper class called AdjacencyList that you can use; it already has a method
written to help with reading the input.
Resource Limits
Yourprogram will be allowed up to 3 seconds of runtime and 32MB of RAM.
programminghomeworkhelp.com
Input Format
Line 1: Twospace-separated integers: N , the number of nodes in the graph, and M , the number of edges.
Lines 2 . . . M : Line i contains three space-separated numbers describing an edge: siand ti , the IDs of the two nodes involved, and wi , the weight of the edge.
Sample input (file mst.in)
6 9
0 1 1.0
1 3 5.0
3 0 3.0
3 4 1.0
1 4 1.0
1 2 6.0
5 2 2.0
2 4 4.0
5 4 4.0
Input Explanation
We can visualize this graph as in Figure 1; let A, B , C , . . . represent the nodes with IDs 0, 1, 2, . . . respectively. Looking at our input file, the we can see that the
second line 0 1 1.0 describes edge between A and B of weight 1.0 in our diagram, the third line 1 3 5.0 describes the edge between B and D of weight 5.0, and so
on. On the right, wecan seeaminimum spanning tree for our graph. Every
Figure 1: The full graph on the left and the minimum spanning tree on the right.
vertex liesin one totally connected component, and the edges here sumto 1.0+1.0+1.0+4.0+2.0 = 9.0, which will be our program’s output.
programminghomeworkhelp.com
Output Format
Line 1: Asingle floating-point number printed to at least 8 decimal digits of precision, representing the total weight of a minimum spanning tree for the provided
graph.
Sample output (file mst.out)
9.00000000
Template Code
If you take a look in the provided template file provided in the file mst.data.zip as a basis for your program, you’ll seesome data structures already written for
you.
#include <vector> class State {
size t node;
double dist; public:
State( size t aNode, double aDist ) : node{aNode}, dist{aDist} {} inline size t node() const { return node; }
inline double dist() const { return dist; }
};
class AdjacencyList {
std::vector< std::vector<State> > vert; AdjacencyList() = delete;
public:
AdjacencyList( std::istream &input );
inline size t size() const { return vert.size(); }
inline const std::vector<State>& vert( size t node ) const { return vert[node];
}
void print();
};
Some questions to ask yourself for understanding:
• What does AdjacencyList() = delete; mean? Why did wedo that?
• This is a fairly complicated line:
inline const std::vector<State>& vert( size t node ) const. Justify or question each use of const.
programminghomeworkhelp.com
•Why don’t we need to write our own destructor for the AdjacencyList class?
•How large is a single instance of the State class in memory, most likely?
Think these questions through and ask about anything that you’re unsure of on
Piazza.
Problem 2
programminghomeworkhelp.com
/*
PROG: mst LANG: C++
*/
#include <vector> #include <queue> #include <fstream>
#include <iostream> #include <iomanip> #include
<unordered_map>
class State { size_t _node; double _dist;
public:
State( size_t aNode, double aDist ) :
_node{aNode}, _dist{aDist} {} inline size_t node()const { return
_node; }
inline double dist()const { return
_dist; }
};
class AdjacencyList {
std::vector< std::vector< State> >
_adj;
AdjacencyList() = delete; public:
AdjacencyList( std::istream &input ); inline size_t size() const {
return
_adj.size(); }
inline const std::vector& adj(size_t node ) const { return
_adj[node]; }
void print();
programminghomeworkhelp.com
};
inline bool operator<( const State &a, const State &b ) {
return a.dist() > b.dist();
}
AdjacencyList::AdjacencyList( std::istream &input ) : _adj{} {
size_t nNodes; size_t nEdges; input >> nNodes >> nEdges;
_adj.resize( nNodes );
for( size_t e = 0; e < nEdges; ++e ) { size_t v, w; double weight;
input >> v >> w >> weight;
// Add this edge to both the v and w lists
_adj[v].push_back( State{ w, weight }
);
_adj[w].push_back( State{ v, weight }
);
}
}
void AdjacencyList::print() {
for( size_t i = 0; i < _adj.size(); ++i
) {
std::cout << i << ": ";
for( auto state : _adj[i] ) { std::cout << "(" << state.node() <<
", " << state.dist() << ") ";
programminghomeworkhelp.com
}
std::cout << "n";
}
}
double prim( const AdjacencyList &adj ) { std::unordered_map<int,
bool> visited; std::priority_queue<State> pq;
pq.push( State{ 0, 0.0 } ); double weight = 0.0;
while( visited.size() < adj.size() ) { auto top = pq.top();
pq.pop();
if( visited.count( top.node() ) == 0 )
{
visited[top.node()] = true; weight += top.dist();
for( auto vertex : adj.adj( top.node() ) ) {
pq.push( vertex );
}
}
}
return weight;
}
programminghomeworkhelp.com
int main() {
std::ifstream input{ "mst.in" }; std::ofstream
output{ "mst.out" };
if( input.is_open() ) {
auto adj = AdjacencyList{ input }; output <<
std::fixed <<
std::setprecision( 8 );
output << prim( adj ) << "n";
} else {
std::cerr << "Could not open mst.inn";
return 1;
}
return 0;
}
Below is the output using the test data:
mst:
1: OK [0.004 seconds]
2: OK [0.004 seconds]
3: OK [0.004 seconds]
4: OK [0.006 seconds]
5: OK [0.093 seconds]
6: OK [0.122 seconds]
7: OK [0.227 seconds]
8: OK [0.229 seconds]
9: OK [0.285 seconds]
10: OK [0.287 seconds]
programminghomeworkhelp.com

Mais conteúdo relacionado

Mais procurados

Variables in matlab
Variables in matlabVariables in matlab
Variables in matlab
TUOS-Sam
 
Minimal spanning tree class 15
Minimal spanning tree class 15Minimal spanning tree class 15
Minimal spanning tree class 15
Kumar
 
Image recogonization
Image recogonizationImage recogonization
Image recogonization
SANTOSH RATH
 
KRUSKAL'S algorithm from chaitra
KRUSKAL'S algorithm from chaitraKRUSKAL'S algorithm from chaitra
KRUSKAL'S algorithm from chaitra
guest1f4fb3
 

Mais procurados (20)

statistics assignment help
statistics assignment helpstatistics assignment help
statistics assignment help
 
Data Analysis Assignment Help
Data Analysis Assignment HelpData Analysis Assignment Help
Data Analysis Assignment Help
 
Data Visualization With R
Data Visualization With RData Visualization With R
Data Visualization With R
 
Electrical Engineering Assignment Help
Electrical Engineering Assignment HelpElectrical Engineering Assignment Help
Electrical Engineering Assignment Help
 
Lecture two
Lecture twoLecture two
Lecture two
 
Variables in matlab
Variables in matlabVariables in matlab
Variables in matlab
 
Optimal Chain Matrix Multiplication Big Data Perspective
Optimal Chain Matrix Multiplication Big Data PerspectiveOptimal Chain Matrix Multiplication Big Data Perspective
Optimal Chain Matrix Multiplication Big Data Perspective
 
Support Vector Machines (SVM)
Support Vector Machines (SVM)Support Vector Machines (SVM)
Support Vector Machines (SVM)
 
FDM Numerical solution of Laplace Equation using MATLAB
FDM Numerical solution of Laplace Equation using MATLABFDM Numerical solution of Laplace Equation using MATLAB
FDM Numerical solution of Laplace Equation using MATLAB
 
Principal component analysis
Principal component analysisPrincipal component analysis
Principal component analysis
 
Some Engg. Applications of Matrices and Partial Derivatives
Some Engg. Applications of Matrices and Partial DerivativesSome Engg. Applications of Matrices and Partial Derivatives
Some Engg. Applications of Matrices and Partial Derivatives
 
Linear models
Linear modelsLinear models
Linear models
 
Minimal spanning tree class 15
Minimal spanning tree class 15Minimal spanning tree class 15
Minimal spanning tree class 15
 
Algorithms explained
Algorithms explainedAlgorithms explained
Algorithms explained
 
PCA and SVD in brief
PCA and SVD in briefPCA and SVD in brief
PCA and SVD in brief
 
Image recogonization
Image recogonizationImage recogonization
Image recogonization
 
Biconnected components (13024116056)
Biconnected components (13024116056)Biconnected components (13024116056)
Biconnected components (13024116056)
 
KRUSKAL'S algorithm from chaitra
KRUSKAL'S algorithm from chaitraKRUSKAL'S algorithm from chaitra
KRUSKAL'S algorithm from chaitra
 
Matlab intro notes
Matlab intro notesMatlab intro notes
Matlab intro notes
 
Spanning trees
Spanning treesSpanning trees
Spanning trees
 

Semelhante a Computer Science Assignment Help

Name _______________________________ Class time __________.docx
Name _______________________________    Class time __________.docxName _______________________________    Class time __________.docx
Name _______________________________ Class time __________.docx
rosemarybdodson23141
 
CIV1900 Matlab - Plotting & Coursework
CIV1900 Matlab - Plotting & CourseworkCIV1900 Matlab - Plotting & Coursework
CIV1900 Matlab - Plotting & Coursework
TUOS-Sam
 
R Programming.pptx
R Programming.pptxR Programming.pptx
R Programming.pptx
kalai75
 
C programming session 05
C programming session 05C programming session 05
C programming session 05
Vivek Singh
 

Semelhante a Computer Science Assignment Help (20)

CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
Analyzing On-Chip Interconnect with Modern C++
Analyzing On-Chip Interconnect with Modern C++Analyzing On-Chip Interconnect with Modern C++
Analyzing On-Chip Interconnect with Modern C++
 
Computation Assignment Help
Computation Assignment Help Computation Assignment Help
Computation Assignment Help
 
R Programming Homework Help
R Programming Homework HelpR Programming Homework Help
R Programming Homework Help
 
theory of computation lecture 01
theory of computation lecture 01theory of computation lecture 01
theory of computation lecture 01
 
Name _______________________________ Class time __________.docx
Name _______________________________    Class time __________.docxName _______________________________    Class time __________.docx
Name _______________________________ Class time __________.docx
 
CIV1900 Matlab - Plotting & Coursework
CIV1900 Matlab - Plotting & CourseworkCIV1900 Matlab - Plotting & Coursework
CIV1900 Matlab - Plotting & Coursework
 
Design of QSD Number System Addition using Delayed Addition Technique
Design of QSD Number System Addition using Delayed Addition TechniqueDesign of QSD Number System Addition using Delayed Addition Technique
Design of QSD Number System Addition using Delayed Addition Technique
 
Design of QSD Number System Addition using Delayed Addition Technique
Design of QSD Number System Addition using Delayed Addition TechniqueDesign of QSD Number System Addition using Delayed Addition Technique
Design of QSD Number System Addition using Delayed Addition Technique
 
B61301007 matlab documentation
B61301007 matlab documentationB61301007 matlab documentation
B61301007 matlab documentation
 
Dijkstra
DijkstraDijkstra
Dijkstra
 
d
dd
d
 
Es272 ch1
Es272 ch1Es272 ch1
Es272 ch1
 
Computational Assignment Help
Computational Assignment HelpComputational Assignment Help
Computational Assignment Help
 
TikZ for economists
TikZ for economistsTikZ for economists
TikZ for economists
 
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : NotesCUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
 
Introduction to r
Introduction to rIntroduction to r
Introduction to r
 
R Programming.pptx
R Programming.pptxR Programming.pptx
R Programming.pptx
 
R data types
R   data typesR   data types
R data types
 
C programming session 05
C programming session 05C programming session 05
C programming session 05
 

Mais de Programming Homework Help

Python Question - Python Assignment Help
Python Question - Python Assignment HelpPython Question - Python Assignment Help
Python Question - Python Assignment Help
Programming Homework Help
 

Mais de Programming Homework Help (20)

C Assignment Help
C Assignment HelpC Assignment Help
C Assignment Help
 
Python Question - Python Assignment Help
Python Question - Python Assignment HelpPython Question - Python Assignment Help
Python Question - Python Assignment Help
 
Best Algorithms Assignment Help
Best Algorithms Assignment Help Best Algorithms Assignment Help
Best Algorithms Assignment Help
 
Design and Analysis of Algorithms Assignment Help
Design and Analysis of Algorithms Assignment HelpDesign and Analysis of Algorithms Assignment Help
Design and Analysis of Algorithms Assignment Help
 
Algorithm Homework Help
Algorithm Homework HelpAlgorithm Homework Help
Algorithm Homework Help
 
programminghomeworkhelp.com_Advanced Algorithms Homework Help.pptx
programminghomeworkhelp.com_Advanced Algorithms Homework Help.pptxprogramminghomeworkhelp.com_Advanced Algorithms Homework Help.pptx
programminghomeworkhelp.com_Advanced Algorithms Homework Help.pptx
 
Algorithm Homework Help
Algorithm Homework HelpAlgorithm Homework Help
Algorithm Homework Help
 
Algorithms Design Assignment Help
Algorithms Design Assignment HelpAlgorithms Design Assignment Help
Algorithms Design Assignment Help
 
Algorithms Design Homework Help
Algorithms Design Homework HelpAlgorithms Design Homework Help
Algorithms Design Homework Help
 
Algorithm Assignment Help
Algorithm Assignment HelpAlgorithm Assignment Help
Algorithm Assignment Help
 
Algorithm Homework Help
Algorithm Homework HelpAlgorithm Homework Help
Algorithm Homework Help
 
C Homework Help
C Homework HelpC Homework Help
C Homework Help
 
C Homework Help
C Homework HelpC Homework Help
C Homework Help
 
Algorithm Assignment Help
Algorithm Assignment HelpAlgorithm Assignment Help
Algorithm Assignment Help
 
Algorithm Homework Help
Algorithm Homework HelpAlgorithm Homework Help
Algorithm Homework Help
 
Computer Science Assignment Help
Computer Science Assignment Help Computer Science Assignment Help
Computer Science Assignment Help
 
Algorithm Assignment Help
Algorithm Assignment HelpAlgorithm Assignment Help
Algorithm Assignment Help
 
Computer Science Assignment Help
Computer Science Assignment HelpComputer Science Assignment Help
Computer Science Assignment Help
 
Software Construction Assignment Help
Software Construction Assignment HelpSoftware Construction Assignment Help
Software Construction Assignment Help
 
C Assignment Help
C Assignment HelpC Assignment Help
C Assignment Help
 

Último

Último (20)

Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
latest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answerslatest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answers
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 

Computer Science Assignment Help

  • 1. Computer Science Assignment Help For any help regarding Computer Assignment Help visit: programminghomeworkhelp.com Email- support@programminghomeworkhelp.com or call us at-+1 678 648 4277 programminghomeworkhelp.com
  • 2. Problem 1: The C++ standard template library provides us with a large number of containers and data structures that we can go ahead and use in our programs. We’ll be learning how to use a priority queue, which is available in the <queue> header. The problem we can solve using a priority queue is that of computing a minimum spanning tree. Given a fully connected undirected graph where each edge has a weight, wewould like to find the set of edges with the least total sum of weights. This may sound abstract; so here’sa concrete scenario: You’re a civil engineer and you’retrying to figure out the best way to arrange for internet accessin your small island nation of C-Land. There areN (3 ≤ N ≤ 250, 000) towns on yourisland connectedbyM (N ≤ M ≤ 250, 000) variousroadsand youcanwalk betweenany two townsonthe island bytraversing somesequenceof roads. However, you’vegot a limited budget and have determined that the cheapest way to arrange for internet access is to build somefiber-optic cables along existing roadways. You have a list of the costsof laying fiber-optic cable down along any particular road, and want to figure out how much money you’ll need to successfullycomplete the project–meaning that, at the end, every town will be connected along somesequence of fiber-optic cables. Luckily, you’re also C-Land’s resident computer scientist, and you remember hearing about Prim’ s algorithm in one of your old programming classes. This algorithm is exactly the solution to yourproblem, but it requires apriorityqueue...and ta-da! Here’ sthe C++ standard template libraryto the rescue. If this scenario is still not totally clear, look at the sample input description on the next page. Our input data describing the graph will be arranged as a list of edges (roads and their fiber-optic cost) and for our program we’ll covert that to an adjacency list: for every node in the graph (town in the country), we’ll have a list of the nodes (towns) it’sconnected to and the weight (cost of building fiber-optic cable along). adj[0]→ (1,1.0) (3,3.0) adj[1]→ (0, 1.0) (2, 6.0) (3, 5.0) (4, 1.0) . . This data structure might be a pain to allocate and keep track of everything in C. The C++ STL will simplify things. First, our adjacency list can be represented as a list of C++ vectors, one for each node. To further simplify and abstract things, we’ve created a wrapper class called AdjacencyList that you can use; it already has a method written to help with reading the input. Resource Limits Yourprogram will be allowed up to 3 seconds of runtime and 32MB of RAM. programminghomeworkhelp.com
  • 3. Input Format Line 1: Twospace-separated integers: N , the number of nodes in the graph, and M , the number of edges. Lines 2 . . . M : Line i contains three space-separated numbers describing an edge: siand ti , the IDs of the two nodes involved, and wi , the weight of the edge. Sample input (file mst.in) 6 9 0 1 1.0 1 3 5.0 3 0 3.0 3 4 1.0 1 4 1.0 1 2 6.0 5 2 2.0 2 4 4.0 5 4 4.0 Input Explanation We can visualize this graph as in Figure 1; let A, B , C , . . . represent the nodes with IDs 0, 1, 2, . . . respectively. Looking at our input file, the we can see that the second line 0 1 1.0 describes edge between A and B of weight 1.0 in our diagram, the third line 1 3 5.0 describes the edge between B and D of weight 5.0, and so on. On the right, wecan seeaminimum spanning tree for our graph. Every Figure 1: The full graph on the left and the minimum spanning tree on the right. vertex liesin one totally connected component, and the edges here sumto 1.0+1.0+1.0+4.0+2.0 = 9.0, which will be our program’s output. programminghomeworkhelp.com
  • 4. Output Format Line 1: Asingle floating-point number printed to at least 8 decimal digits of precision, representing the total weight of a minimum spanning tree for the provided graph. Sample output (file mst.out) 9.00000000 Template Code If you take a look in the provided template file provided in the file mst.data.zip as a basis for your program, you’ll seesome data structures already written for you. #include <vector> class State { size t node; double dist; public: State( size t aNode, double aDist ) : node{aNode}, dist{aDist} {} inline size t node() const { return node; } inline double dist() const { return dist; } }; class AdjacencyList { std::vector< std::vector<State> > vert; AdjacencyList() = delete; public: AdjacencyList( std::istream &input ); inline size t size() const { return vert.size(); } inline const std::vector<State>& vert( size t node ) const { return vert[node]; } void print(); }; Some questions to ask yourself for understanding: • What does AdjacencyList() = delete; mean? Why did wedo that? • This is a fairly complicated line: inline const std::vector<State>& vert( size t node ) const. Justify or question each use of const. programminghomeworkhelp.com
  • 5. •Why don’t we need to write our own destructor for the AdjacencyList class? •How large is a single instance of the State class in memory, most likely? Think these questions through and ask about anything that you’re unsure of on Piazza. Problem 2 programminghomeworkhelp.com
  • 6. /* PROG: mst LANG: C++ */ #include <vector> #include <queue> #include <fstream> #include <iostream> #include <iomanip> #include <unordered_map> class State { size_t _node; double _dist; public: State( size_t aNode, double aDist ) : _node{aNode}, _dist{aDist} {} inline size_t node()const { return _node; } inline double dist()const { return _dist; } }; class AdjacencyList { std::vector< std::vector< State> > _adj; AdjacencyList() = delete; public: AdjacencyList( std::istream &input ); inline size_t size() const { return _adj.size(); } inline const std::vector& adj(size_t node ) const { return _adj[node]; } void print(); programminghomeworkhelp.com
  • 7. }; inline bool operator<( const State &a, const State &b ) { return a.dist() > b.dist(); } AdjacencyList::AdjacencyList( std::istream &input ) : _adj{} { size_t nNodes; size_t nEdges; input >> nNodes >> nEdges; _adj.resize( nNodes ); for( size_t e = 0; e < nEdges; ++e ) { size_t v, w; double weight; input >> v >> w >> weight; // Add this edge to both the v and w lists _adj[v].push_back( State{ w, weight } ); _adj[w].push_back( State{ v, weight } ); } } void AdjacencyList::print() { for( size_t i = 0; i < _adj.size(); ++i ) { std::cout << i << ": "; for( auto state : _adj[i] ) { std::cout << "(" << state.node() << ", " << state.dist() << ") "; programminghomeworkhelp.com
  • 8. } std::cout << "n"; } } double prim( const AdjacencyList &adj ) { std::unordered_map<int, bool> visited; std::priority_queue<State> pq; pq.push( State{ 0, 0.0 } ); double weight = 0.0; while( visited.size() < adj.size() ) { auto top = pq.top(); pq.pop(); if( visited.count( top.node() ) == 0 ) { visited[top.node()] = true; weight += top.dist(); for( auto vertex : adj.adj( top.node() ) ) { pq.push( vertex ); } } } return weight; } programminghomeworkhelp.com
  • 9. int main() { std::ifstream input{ "mst.in" }; std::ofstream output{ "mst.out" }; if( input.is_open() ) { auto adj = AdjacencyList{ input }; output << std::fixed << std::setprecision( 8 ); output << prim( adj ) << "n"; } else { std::cerr << "Could not open mst.inn"; return 1; } return 0; } Below is the output using the test data: mst: 1: OK [0.004 seconds] 2: OK [0.004 seconds] 3: OK [0.004 seconds] 4: OK [0.006 seconds] 5: OK [0.093 seconds] 6: OK [0.122 seconds] 7: OK [0.227 seconds] 8: OK [0.229 seconds] 9: OK [0.285 seconds] 10: OK [0.287 seconds] programminghomeworkhelp.com