Editing
2019 Dec Silver Problem 3 Milk Visits
(section)
Jump to navigation
Jump to search
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== Solution == The solution to this problem can be found using the Travelling Salesman Problem (TSP) algorithm. This algorithm can be used to find the shortest route that visits each cow exactly once and returns to the house. In C++, the algorithm can be implemented as follows: <pre> #include <vector> #include <algorithm> using namespace std; // Function to find the shortest route // that visits each cow exactly once // and returns to the house int tsp(vector<vector<int>>& graph, vector<bool>& visited, int currPos, int n, int count, int cost) { // If all cows are visited if (count == n) { // Return cost of the route return cost + graph[currPos][0]; } // Initialize result int res = INT_MAX; // Try all unvisited cows for (int i = 0; i < n; i++) { if (!visited[i]) { // Mark cow as visited visited[i] = true; // Calculate cost of the route int newCost = cost + graph[currPos][i]; // Recur for remaining cows res = min(res, tsp(graph, visited, i, n, count + 1, newCost)); // Mark cow as unvisited visited[i] = false; } } return res; } int main() { // Number of cows int n = 5; // Adjacency matrix vector<vector<int>> graph = { { 0, 10, 15, 20 }, { 10, 0, 35, 25 }, { 15, 35, 0, 30 }, { 20, 25, 30, 0 } }; // Visited array to keep track // of visited cows vector<bool> visited(n); // Initialize result int res = INT_MAX; // Find the shortest route res = tsp(graph, visited, 0, n, 0, 0); // Print result cout << res << endl; return 0; } </pre> [[Category:Yearly_2019_2020]] [[Category:Silver]] [[Category:DFS]] [[Category:Graph]] [[Category:Tree]]
Summary:
Please note that all contributions to Wiki may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
My wiki:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Navigation menu
Personal tools
Not logged in
Talk
Contributions
Create account
Log in
Namespaces
Page
Discussion
English
Views
Read
Edit
View history
More
Search
Navigation
Main page
Recent changes
Random page
Help about MediaWiki
Tools
What links here
Related changes
Special pages
Page information