SlideShare a Scribd company logo
1 of 3
Download to read offline
Ví dụ về tìm đường đi ngắn nhất bằng thuật toán Bellman Ford Nguyễn Hữu Tuân – vimaru.edu.vn
1
Các đồ thị ví dụ:
Hình 1: Đơn đồ thị có trọng số.
Chương trình cài đặt thuật toán tìm đường đi ngắn nhất bằng thuật toán Bellman Ford với có trọng số được biểu
diễn bằng ma trận kề. Với đồ thị trên, ma trận kề tương ứng sẽ là:
6
0 33 17 0 0 0
33 0 18 30 0 0
17 18 0 16 4 0
0 20 16 0 9 8
0 0 4 9 0 14
0 0 0 8 14 0
Sau đây là chương trình (graph_bellman1.cpp) đọc đồ thị biểu diễn ở dạng ma trận kề (từ bàn phím hoặc từ file),
sau đó tìm và in ra đường đi ngắn nhất giữa 2 đỉnh (nhập từ bàn phím) của đồ thị bằng thuật toán Bellman Ford.
// Single source shortest paths using Bellman Ford algorithm
// Author: Huu-Tuan Nguyen
// Lecturer at the FIT, Vietnam Maritime University
// Date: 24/11/2015
// Require: C++ 11 supported compiler
#include <iostream> // for cin, cout
#include <fstream> // for file stream
#include <vector> // for vector
using namespace std;
void print_path(int v, int u, vector<int> & prev);
struct Edge {
int start;
int end;
int weight;
};
int main(int argc, char * argv[]) // argc: argument count, argv: argument values
{
Ví dụ về tìm đường đi ngắn nhất bằng thuật toán Bellman Ford Nguyễn Hữu Tuân – vimaru.edu.vn
2
int n;
vector<vector<int>> vvi(n, vector<int>(n, 0));
int i, j;
if (argc>1)
{
if (atoi(argv[1]) == 0)
{
cout << "Nhap so dinh cua do thi n=";
cin >> n;
vvi = vector<vector<int>>(n, vector<int>(n, 0)); // khai bao n vector, moi vector co n
phan tu
for (i = 0; i<n; i++)
for (j = i + 1; j<n; j++)
{
cout << "Nhap a[" << i << "][" << j << "]=";
cin >> vvi[i][j];
vvi[j][i] = vvi[i][j];
}
}
else if (argc == 3)
{
ifstream fin(argv[2]); // mo file
fin >> n;
vvi = vector<vector<int>>(n, vector<int>(n, 0)); // khai bao n vector, moi vector co n
phan tu
for (i = 0; i<n; i++)
for (j = 0; j<n; j++)
{
fin >> vvi[i][j];
vvi[j][i] = vvi[i][j];
}
fin.close(); // dong file
}
vector<Edge> edges;
for (i = 0; i<n; i++)
for (j = i + 1; j<n; j++)
if (vvi[i][j]>0)
edges.emplace_back((Edge) { i, j, vvi[i][j] });
int INF = int(10e8); // infinitive value
int startV, endV;
cout << "Nhap dinh xuat phat:";
cin >> startV;
cout << "Nhap dinh ket thuc:";
cin >> endV;
vector<int> prev(n, startV); // make all the vertices to have their previous one to be
startV
vector<int> dist(n, INF); // initialize all vertices with infinitive distances
dist[startV] = 0;
for (i = 0; i<n; i++)
for (auto & edge : edges)
{
int u = edge.start; // first component: the vertex u
Ví dụ về tìm đường đi ngắn nhất bằng thuật toán Bellman Ford Nguyễn Hữu Tuân – vimaru.edu.vn
3
int v = edge.end; // second component: the vertex v
int w = edge.weight; // third component: the weight of edge[u,v]
if (dist[v]>dist[u] + w)
{
dist[v] = dist[u] + w;
prev[v] = u;
}
}
// recheck whether there exists a negative circuit in the graph
bool negCirFlag = false;
for (auto & edge : edges)
{
int u = edge.start; // first component: the vertex u
int v = edge.end; // second component: the vertex v
int w = edge.weight; // third component: the weight of edge[u,v]
if (dist[v]>dist[u] + w)
{
cerr << "Do thi co chu trinh am";
negCirFlag = true;
break;
}
}
if (!negCirFlag)
{
cout << "Duong di ngan nhat tu dinh " << startV << " toi dinh " << endV << " la " <<
dist[endV] << endl;
print_path(startV, endV, prev);
}
}
else
cout << "Chay chuong trinh nhu sau:<ten chuong trinh> <0:nhap tu ban phim,1: nhap tu file>
<ten file>";
return 0;
}
void print_path(int v, int u, vector<int> & prev)
{
if (prev[u] == v)
cout << v << "-->" << u;
else
{
print_path(v, prev[u], prev);
cout << "-->" << u;
}
}

More Related Content

Featured

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Ly thuyet do_thi_-_shortest_path_-_bellman_ford_-_vimaru.edu_.vn_

  • 1. Ví dụ về tìm đường đi ngắn nhất bằng thuật toán Bellman Ford Nguyễn Hữu Tuân – vimaru.edu.vn 1 Các đồ thị ví dụ: Hình 1: Đơn đồ thị có trọng số. Chương trình cài đặt thuật toán tìm đường đi ngắn nhất bằng thuật toán Bellman Ford với có trọng số được biểu diễn bằng ma trận kề. Với đồ thị trên, ma trận kề tương ứng sẽ là: 6 0 33 17 0 0 0 33 0 18 30 0 0 17 18 0 16 4 0 0 20 16 0 9 8 0 0 4 9 0 14 0 0 0 8 14 0 Sau đây là chương trình (graph_bellman1.cpp) đọc đồ thị biểu diễn ở dạng ma trận kề (từ bàn phím hoặc từ file), sau đó tìm và in ra đường đi ngắn nhất giữa 2 đỉnh (nhập từ bàn phím) của đồ thị bằng thuật toán Bellman Ford. // Single source shortest paths using Bellman Ford algorithm // Author: Huu-Tuan Nguyen // Lecturer at the FIT, Vietnam Maritime University // Date: 24/11/2015 // Require: C++ 11 supported compiler #include <iostream> // for cin, cout #include <fstream> // for file stream #include <vector> // for vector using namespace std; void print_path(int v, int u, vector<int> & prev); struct Edge { int start; int end; int weight; }; int main(int argc, char * argv[]) // argc: argument count, argv: argument values {
  • 2. Ví dụ về tìm đường đi ngắn nhất bằng thuật toán Bellman Ford Nguyễn Hữu Tuân – vimaru.edu.vn 2 int n; vector<vector<int>> vvi(n, vector<int>(n, 0)); int i, j; if (argc>1) { if (atoi(argv[1]) == 0) { cout << "Nhap so dinh cua do thi n="; cin >> n; vvi = vector<vector<int>>(n, vector<int>(n, 0)); // khai bao n vector, moi vector co n phan tu for (i = 0; i<n; i++) for (j = i + 1; j<n; j++) { cout << "Nhap a[" << i << "][" << j << "]="; cin >> vvi[i][j]; vvi[j][i] = vvi[i][j]; } } else if (argc == 3) { ifstream fin(argv[2]); // mo file fin >> n; vvi = vector<vector<int>>(n, vector<int>(n, 0)); // khai bao n vector, moi vector co n phan tu for (i = 0; i<n; i++) for (j = 0; j<n; j++) { fin >> vvi[i][j]; vvi[j][i] = vvi[i][j]; } fin.close(); // dong file } vector<Edge> edges; for (i = 0; i<n; i++) for (j = i + 1; j<n; j++) if (vvi[i][j]>0) edges.emplace_back((Edge) { i, j, vvi[i][j] }); int INF = int(10e8); // infinitive value int startV, endV; cout << "Nhap dinh xuat phat:"; cin >> startV; cout << "Nhap dinh ket thuc:"; cin >> endV; vector<int> prev(n, startV); // make all the vertices to have their previous one to be startV vector<int> dist(n, INF); // initialize all vertices with infinitive distances dist[startV] = 0; for (i = 0; i<n; i++) for (auto & edge : edges) { int u = edge.start; // first component: the vertex u
  • 3. Ví dụ về tìm đường đi ngắn nhất bằng thuật toán Bellman Ford Nguyễn Hữu Tuân – vimaru.edu.vn 3 int v = edge.end; // second component: the vertex v int w = edge.weight; // third component: the weight of edge[u,v] if (dist[v]>dist[u] + w) { dist[v] = dist[u] + w; prev[v] = u; } } // recheck whether there exists a negative circuit in the graph bool negCirFlag = false; for (auto & edge : edges) { int u = edge.start; // first component: the vertex u int v = edge.end; // second component: the vertex v int w = edge.weight; // third component: the weight of edge[u,v] if (dist[v]>dist[u] + w) { cerr << "Do thi co chu trinh am"; negCirFlag = true; break; } } if (!negCirFlag) { cout << "Duong di ngan nhat tu dinh " << startV << " toi dinh " << endV << " la " << dist[endV] << endl; print_path(startV, endV, prev); } } else cout << "Chay chuong trinh nhu sau:<ten chuong trinh> <0:nhap tu ban phim,1: nhap tu file> <ten file>"; return 0; } void print_path(int v, int u, vector<int> & prev) { if (prev[u] == v) cout << v << "-->" << u; else { print_path(v, prev[u], prev); cout << "-->" << u; } }