Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <vector>
- using namespace std;
- class Edge
- {
- public:
- int a;
- int b;
- long long weight;
- Edge(int x, int y, long long value)
- {
- a = x;
- b = y;
- weight = value;
- }
- };
- vector< pair<long long, bool> > distances;
- vector<int> *buff;
- vector<Edge> edges;
- int n, m, s;
- ifstream InputFile("path.in");
- ofstream OutputFile("path.out");
- vector<int> cycle(vector<Edge> e, int n, int m) {
- vector<long long> d (n);
- vector<int> p (n, -1);
- int x;
- for (int i = 0; i < n; ++i) {
- x = -1;
- for (int j = 0; j < m; ++j)
- if (d[e[j].b] > d[e[j].a] + e[j].weight) {
- d[e[j].b] = max (-LONG_LONG_MAX, d[e[j].a] + e[j].weight);
- p[e[j].b] = e[j].a;
- x = e[j].b;
- }
- }
- vector<int> path;
- if (x == -1)
- return path;
- else {
- int y = x;
- for (int i=0; i<n; ++i)
- y = p[y];
- for (int cur=y; ; cur=p[cur]) {
- path.push_back (cur);
- if (cur == y && path.size() > 1) break;
- }
- return path;
- }
- }
- void dfs(int p)
- {
- distances[p].second = false;
- for (int i = 0; i < buff[p].size(); i++)
- {
- if (distances[buff[p][i]].second) {
- dfs(buff[p][i]);
- }
- }
- }
- void solve()
- {
- for (int i = 0; i < distances.size(); i++)
- {
- for (int j = 0; j < edges.size(); j++)
- {
- if (distances[edges[j].a].first < LONG_LONG_MAX)
- {
- if (distances[edges[j].b].first > distances[edges[j].a].first + edges[j].weight)
- {
- if (distances[edges[j].a].first + edges[j].weight > 0 || (distances[edges[j].a].first < 0 || edges[j].weight < 0))
- distances[edges[j].b].first = distances[edges[j].a].first + edges[j].weight;
- }
- }
- }
- }
- vector<int> cycled = cycle(edges, n, m);
- if (!cycled.empty())
- dfs(cycled[0]);
- distances[s].second = true;
- for (int i = 0; i < distances.size(); i++)
- {
- if (!distances[i].second)
- OutputFile << "-\n";
- else if (distances[i].first == LONG_LONG_MAX)
- OutputFile << "*\n";
- else
- OutputFile << distances[i].first << "\n";
- }
- }
- int main()
- {
- int firstNode, secondNode;
- long long distance;
- InputFile >> n >> m >> s;
- s--;
- buff = new vector<int>[n];
- distances.resize(n, make_pair(LONG_LONG_MAX, true));
- distances[s].first = 0;
- for (int i = 0; i < m; i++)
- {
- InputFile >> firstNode >> secondNode >> distance;
- firstNode--;
- secondNode--;
- buff[firstNode].push_back(secondNode);
- edges.emplace_back(firstNode, secondNode, distance);
- }
- solve();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement