Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- const int N = (int) 5e1;
- const int inf = (int) 1e9;
- struct Matrix {
- vector<vector<int>> mat;
- Matrix() {
- }
- Matrix(int n) {
- mat = vector<vector<int>>(n, vector<int>(n, inf));
- }
- Matrix(vector<vector<int>> _mat) {
- mat = _mat;
- }
- void print() {
- int n = mat.size();
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < n; j++) {
- printf("%d%c", mat[i][j], " \n"[j + 1 == n]);
- }
- }
- }
- friend Matrix operator * (Matrix a, Matrix b) { // a, b - square matrices
- int n = a.mat.size();
- Matrix c = Matrix(n);
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < n; j++) {
- for (int k = 0; k < n; k++) {
- if (a.mat[i][k] == inf || b.mat[k][j] == inf) {
- continue;
- }
- int v = a.mat[i][k] + b.mat[k][j];
- if (k == 0) {
- c.mat[i][j] = v;
- } else {
- c.mat[i][j] = min(c.mat[i][j], v);
- }
- }
- }
- }
- return c;
- }
- friend void operator *= (Matrix &a, Matrix b) {
- a = a * b;
- }
- void operator = (Matrix b) {
- mat = b.mat;
- }
- } g;
- int n;
- bool vis[N];
- void dfs(int v) {
- for (int i = 0; i < n; i++) {
- if (!vis[i] && g.mat[v][i] != inf) {
- vis[i] = true;
- dfs(i);
- }
- }
- }
- Matrix bin_pow(Matrix a, int n) {
- Matrix r = a;
- --n;
- while (n > 0) {
- if (n & 1) {
- if (r.mat.empty()) {
- r = a;
- } else {
- r *= a;
- }
- }
- a *= a;
- n >>= 1;
- }
- return r;
- }
- int main() {
- int m, s, t;
- cin >> n >> m >> s >> t;
- --s;
- --t;
- g = Matrix(n);
- for (int i = 0; i < m; i++) {
- int x, y, l;
- cin >> x >> y >> l;
- --x;
- --y;
- g.mat[x][y] = min(g.mat[x][y], l);
- g.mat[y][x] = min(g.mat[y][x], l);
- }
- dfs(s);
- if (vis[s] && vis[t]) {
- Matrix res = bin_pow(g, 2018);
- while (true) {
- if (res.mat[s][t] != inf) {
- cout << res.mat[s][t] << "\n";
- break;
- } else {
- res *= res;
- res *= g;
- }
- }
- } else {
- puts("Mumkun emes");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement