aboutsummaryrefslogtreecommitdiff
path: root/Semestr 4/aisd/themis/BELLMAN.cpp
blob: 5a650961361db1372385fecd2e8f09a4c4b74d46 (plain)
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <bits/stdc++.h>
using namespace std;

const int N = 503;
int dist[N];
vector<pair<int, pair<int, int>>> edges;
int main()
{
  ios_base::sync_with_stdio(false);
  cin.tie();
  int n, m, s;
  cin >> n >> m >> s;
  for (int i = 0; i <= n; i++)
  {
    dist[i] = 2e9;
  }
  dist[s] = 0;
  for (int i = 0; i < m; i++)
  {
    int u, v, w;
    cin >> u >> v >> w;
    edges.push_back({w, {u, v}});
    // edges.push_back({w, {v, u}});
  }

  for (int i = 0; i < n + 1; i++)
  {
    for (auto e : edges)
    {
      int w = e.first;
      int u = e.second.first;
      int v = e.second.second;
      if (dist[v] > dist[u] + w)
      {
        dist[v] = dist[u] + w;
      }
    }
  }
  for (auto e : edges)
  {
    int w = e.first;
    int u = e.second.first;
    int v = e.second.second;
    if (dist[v] > dist[u] + w)
    {
      cout << "NIE\n";
      return 0;
    }
  }
  for (int i = 0; i < n; i++)
  {
    if (i != s && dist[i] < 1e9)
      cout << i << " " << dist[i] << "\n";
  }
}