-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.cpp
164 lines (108 loc) · 2.05 KB
/
graph.cpp
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#include<cstdio>
#include<iostream>
#include<string>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<sstream>
#include<limits.h>
#include<list>
#include<stack>
#include<queue>
#include<map>
using namespace std;
typedef pair<int, int> ii;
typedef long long int64;
#define Max 15100
#define INF 2000000000
#define TRvi(c, it) \
for(vector<int>::iterator it = c.begin(); it != c.end(); it++)
int V, E;
vector<int> cost;
vector<vector<int> > reverseGraph;
int64 dp[Max];
int visited[Max];
vector<int> topoSort;
void topologicalSorting(int node)
{
int next;
visited[node] = 1;
TRvi(reverseGraph[node], v)
{
next = *v;
if(!visited[next])
topologicalSorting(next);
}
topoSort.push_back(node);
}
void createDP()
{
int node, prev;
int64 res;
for(int i = 0; i < V; i++)
{
node = topoSort[i];
if(reverseGraph[node].size() == 0) /* no indegree */
dp[node] = cost[node];
else
{
res = -INF;
TRvi(reverseGraph[node], v)
{
prev = *v;
res = max(res, dp[prev]);
}
if(res + cost[node] < cost[node])
dp[node] = cost[node];
else
dp[node] = res + cost[node];
}
}
}
int main()
{
FILE* fin = freopen("easygraph.in", "r", stdin);
FILE* fout = freopen("easygraph.out", "w", stdout);
int src, dest;
int T; cin >> T;
while(T--)
{
scanf("%d%d", &V, &E);
cost.clear();
cost.resize(V);
for(int i = 0; i < V; i++)
scanf("%d", &cost[i]);
reverseGraph.clear();
reverseGraph.resize(V);
for(int i = 0; i < E; i++)
{
scanf("%d%d", &src, &dest);
src--; dest--;
reverseGraph[dest].push_back(src);
}
/* sort vertices */
topoSort.clear();
memset(visited, 0, sizeof(visited));
for(int node = 0; node < V; node++)
{
if(!visited[node])
topologicalSorting(node);
}
int64 res = -INF;
//memset(dp, -1, sizeof(dp));
createDP();
for(int node = 0; node < V; node++)
if(res < dp[node])
res = dp[node];
/*
while(true)
{
int a; cin >> a; a--;
cout << endingHere(a) << endl;
} */
cout << res << endl;
}
fclose(fin);
fclose(fout);
return 0;
}