-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHW11-LongestPath.cpp
More file actions
78 lines (66 loc) · 1.72 KB
/
HW11-LongestPath.cpp
File metadata and controls
78 lines (66 loc) · 1.72 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
struct Relation
{
int from, to;
long long int weight;
Relation (int from, int to,
long long int weight)
{
this->from = from;
this->to = to;
this->weight = weight;
}
};
class Graph
{
public:
vector<Relation*> rels;
void relate(int u, int v, long long int w)
{
rels.push_back(new Relation(u, v, w));
}
void longestPath(int startVertex, int endVertex, int vCount, int eCount)
{
vector<long long int> dist(vCount + 1, LLONG_MIN);
dist[startVertex] = 0;
for (int i = 0; i < vCount; i++)
{
for (int j = 0; j < eCount; j++)
{
Relation* curRel = rels[j];
if (dist[curRel->from] != LLONG_MIN)
{
int newDist = dist[curRel->from] + curRel->weight;
if (dist[curRel->to] < newDist)
dist[curRel->to] = newDist;
}
}
}
// Print result
if (dist[endVertex] == LLONG_MIN)
{
cout << "-1" << endl;
return;
}
cout << dist[endVertex] << endl;
}
};
int main () {
// Initialize
Graph graph;
int vCount, eCount, startVertex, endVertex;
cin >> vCount >> eCount >> startVertex >> endVertex;
// Create Relations
int from, to;
long long int weight;
for (int i = 0; i < eCount; i++)
{
cin >> from >> to >> weight;
graph.relate(from, to, weight);
}
// Print Longest Path
graph.longestPath(startVertex, endVertex, vCount, eCount);
}