/*
Bismillahir Rahmamir Rahim
Implementing BFS algorithm with c++
*/
#include<bits/stdc++.h>
using namespace std;
vector<int>vt[100];
queue<int>q;
int cost[100][100], dis[100], visit[100];
void bfs(int st){
for(int i=0; i<=100; i++){
dis[i]=100009, visit[i]=0;
}
int p, y, cst;
dis[st]=0;
q.push(st);
while(!q.empty()){
p=q.front();
q.pop();
if(!visit[p]){
for(int i=0; i<vt[p].size(); i++){
y=vt[p][i];
cst=cost[p][y]+dis[p];
if(cst<dis[y]){
dis[y]=cst;
q.push(y);
}
}
visit[p]=1;
}
}
}
int main(){
int n1, n2, edge, c, x;
cin>>edge;
for(int i=0; i<edge; i++){
cin>>n1>>n2>>c;
vt[n1].push_back(n2);
vt[n2].push_back(n1);
cost[n1][n2]=cost[n2][n1]=c;
}
bfs(1);
while(cin>>x) cout<<dis[x]<<endl;
return 0;
}
|
Saturday, February 18, 2017
BFS Algorithm - Implementation with C++
Subscribe to:
Post Comments (Atom)
-
#include<bits/stdc++.h> #define ll long long using namespace std ; ll n , k , t_case ; ll bigmod ( ll b , ll p , ll m...
-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 ...
-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 3...
No comments:
Post a Comment