Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<fstream>
- #include<cmath>
- #include <stdio.h>
- using namespace std;
- struct graph
- {
- int x;
- int y;
- int weight;
- };
- struct node
- {
- graph G;
- node* next;
- };
- void push (node* &p, graph G)
- {
- node *temp;
- temp = new node;
- temp->G = G;
- temp->next =p;
- p = temp;
- }
- void show (node* &p)
- {
- while (p)
- {
- cout<<p->G.x <<" "<< p->G.y << " "<<p->G.weight<<endl;
- p = p->next;
- }
- }
- void read (node* &p,ifstream &file)
- {
- p = NULL;
- graph g;
- while (file >> g.x >>g.y >> g.weight)
- {
- push(p, g);
- }
- }
- void write (node* p,ofstream &out)
- {
- while (p)
- {
- out<<p->G.x <<" "<< p->G.y << " "<<p->G.weight<<endl;
- p = p->next;
- }
- }
- void show_matrix (ofstream &fout, int **matrix,int N)
- {
- for (int i=0;i<N;i++)
- {
- for (int j=0;j<N;j++)
- {
- fout<<matrix[i][j]<<" ";
- }
- fout<<endl;
- }
- }
- void read_matrix (ifstream &fin, int matrix[6][6],int N)
- {
- {
- for (int i=0;i<N;i++)
- {
- for (int j=0;j<N;j++)
- {
- fin>>matrix[i][j];
- }
- }
- }
- }
- void search (node *p, int n)
- {
- node* tmp = p;
- int counter = 0;
- while (p)
- {
- if (tmp->G.x == n|| tmp->G.y ==n)
- {
- counter++;
- }
- tmp = tmp->next;
- }
- cout<<counter;
- }
- void opway (int matrix[6][6], int N)
- {
- int minW[N];
- int checked[N];
- int temp, minindex, min;
- int start_index = 0;
- for (int i = 0; i<N; i++)
- {
- for (int j = 0; j<N; j++)
- cout<<matrix[i][j]<<" ";
- cout<<endl;
- }
- for (int i = 0; i<N; i++)
- {
- minW[i] = 10000;
- checked[i] = 1;
- }
- minW[start_index] = 0;
- while (minindex < 10000) {
- minindex = 10000;
- min = 10000;
- for (int i = 0; i<N; i++)
- {
- if ((checked[i] == 1) && (minW[i]<min))
- {
- min = minW[i];
- minindex = i;
- }
- }
- if (minindex != 10000)
- {
- for (int i = 0; i<N; i++)
- {
- if (matrix[minindex][i] > 0)
- {
- temp = min + matrix[minindex][i];
- if (temp < minW[i])
- {
- minW[i] = temp;
- }
- }
- }
- checked[minindex] = 0;
- }
- }
- int cchecked[N];
- int end = 4;
- cchecked[0] = end + 1;
- int k = 1;
- int weight = minW[end];
- while (end != start_index)
- {
- for (int i = 0; i<N; i++)
- if (matrix[i][end] != 0)
- {
- int temp = weight - matrix[i][end];
- if (temp == minW[i])
- {
- weight = temp;
- end = i;
- cchecked[k] = i + 1;
- k++;
- }
- }
- }
- cout<<endl<<"Кратчайший путь: "<<endl;
- for (int i=k-1;i>=0;i--)
- {
- cout<<cchecked[i]<<" ";
- }
- cout<<endl;
- }
- int main()
- {
- ifstream fin ("input.txt");
- ofstream fout ("output.txt");
- int N = 6;
- int matrix[6][6];
- read_matrix(fin,matrix,N);
- opway(matrix, N);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement