[Luo Gu P1938] to find a job Employment Job Hunt

Description

Given a directed graph right point (of course you can also be understood as the right side) which is a point d or zd seeking the maximum weight value and outputs the weights if unlimited increase in the weight outputs -1

Solution

Because unlimited increase in weight is a ring so we thought of such an algorithm can determine the ring:

SPFA! Of course not purely SPFA we can use the priority queue (small heap root) to optimize

We point the right to be seen as the right side without having to spend money, then if the right side is d if it takes the right side, then ran from the starting point to zd s longest single-source side SPFA seeking a way to take the last maximum on it

 How to judge a ring?

We use an array to record times at this point is slack several times according to the principles relaxed if a point is> = n times is the emergence of a ring

Code

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <queue>
 4 #include <cstdlib>
 5 using namespace std;
 6 int d, p, c, f, s, num;
 7 int head[1100], dis[1100], vis[1100], times[1100];
 8 priority_queue<int, vector<int>, greater<int> >q;
 9 struct emmm {
10     int next, to, dis;
11 }e[1100];
12 void add(int from, int to, int dis) {
13     e[++num].next = head[from];
14     e[num].to = to;
15     e[num].dis = dis;
16     head[from] = num;
17 }
18 void spfa(int s) {
19     q.push(s);
20     vis[s] = 1;
21     dis[s] = d;
22     times[s]++;
23     while (!q.empty()) {
24         int now = q.top();
25         q.pop();
26         vis[s] = 0;
27         for (int i = head[now];i; i = e[i].next) {
28             int v = e[i].to;
29             if (dis[v] < dis[now] + e[i].dis) {
30                 dis[v] = dis[now] + e[i].dis;
31                 if (!vis[v]) {
32                     q.push(v);
33                     vis[v] = 1;
34                     times[v]++;
35                     if (times[v] >= c) cout << -1 << endl, exit(0);
36                 }
37             }
38         }
39     }
40 }
41 int main() {
42     ios::sync_with_stdio(false);
43     cin >> d >> p >> c >> f >> s;
44     int x, y, z;
45     for (int i = 1;i <= p; i++) {
46         cin >> x >> y;
47         add(x, y, d);
48     }
49     for (int i = 1;i <= f; i++) {
50         cin >> x >> y >> z;
51         add(x, y, d-z);
52     }
53     spfa(s);
54     int ans = 0;
55     for (int i = 1;i <= c; i++) 
56         ans = max(ans, dis[i]);
57     cout << ans << endl;
58     return 0;
59 }
AC Code

 

Guess you like

Origin www.cnblogs.com/-sheldon/p/11369702.html