Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdio>
- #include <vector>
- #include <iostream>
- using namespace std;
- struct Vertex;
- struct Edge{
- Vertex* neighbour;
- int weight;
- };
- static const size_t INF = 1 << 30;
- struct Vertex{
- bool visited = false;
- size_t distance = INF;
- void add_edge(Vertex* neighbour, int weight){
- out_edges_.push_back({neighbour, weight});
- }
- vector<Edge> get_neighbours(){
- return out_edges_;
- };
- private:
- vector<Edge> out_edges_;
- };
- class WeightedGraph{
- public:
- explicit WeightedGraph(int v) : graph_(v+1), v_amount_(v){}
- void add_edge(int a, int b, int weight){
- graph_[a+1].add_edge(&graph_[b+1], weight);
- }
- size_t get_path_length(int start, int finish){
- //TODO dijkstra algorithm
- // 1) get minimum distance vertex (linear complexity) done
- // 2) relaxation (done)
- graph_[start].distance = 0;
- graph_[start].visited = true;
- relaxation(start);
- for (int step = 0; step < v_amount_-1; ++step){
- auto mn = find_minimum_distance_vertex();
- relaxation(mn);
- }
- auto result = graph_[finish].distance;
- return result;
- }
- private:
- int find_minimum_distance_vertex(){
- size_t mn = INF;
- int result = -1;
- for (int i = 1; i < v_amount_+1; ++i){
- if (!graph_[i].visited && graph_[i].distance < mn){
- mn = graph_[i].distance;
- result = i;
- }
- }
- return result;
- }
- void relaxation(int v_ind){
- auto v = &graph_[v_ind];
- v->visited = true;
- for (auto [neighbour, weight] : v->get_neighbours()){
- if (neighbour->distance > v->distance + weight){
- neighbour->distance = v->distance + weight;
- }
- }
- }
- vector<Vertex> graph_;
- int v_amount_;
- };
- int main(){
- int v_amount, start, finish;
- scanf("%d%d%d",&v_amount, &start, &finish);
- WeightedGraph graph(v_amount);
- for (int v = 0; v < v_amount; ++v){
- for (int neighbour = 0; neighbour < v_amount; ++neighbour){
- int weight = 0;
- scanf("%d", &weight);
- if (neighbour == v){
- continue;
- }
- if (weight != -1){
- graph.add_edge(v, neighbour, weight);
- }
- }
- }
- // WeightedGraph graph(6);
- // int start = 1;
- // int finish = 6 ;
- //
- // for (int i = 0; i < 7; ++i){
- // int a, b, weight;
- // cin >> a >> b >> weight;
- // graph.add_edge(a-1, b-1, weight);
- // }
- size_t path_length = graph.get_path_length(start, finish);
- if (path_length == INF){
- cout << -1;
- return 0;
- }
- cout << path_length;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement