P1938
P1938题解
这到题可以使用SPFA来解 。
题目要求的是 :求出在图上经过的点的最大值,也就是赚的钱的数量是多少。如果是无穷大(也就是存在正环),那么输出-1。
我们都知道SPFA只能求出在图上经过的边的最大值,所以我们可以把点权化边权,将免费的边权权值定为点权设为D,有费的边权变为D - Ci即可,让后就可以用SPFA正常的做最长路就行。
不过还有有正环的情况,仔细想想会发现如果真的有正环那么因为我们是求最长路。所以我们必定经过所以经过点数肯定大于等于N。所以我们只需定义一个cnt,数组来记录当前是在第几步。如果cnt >= n那么存在负环。
注释 : 起点也可以赚钱。
SPFA代码
int spfa(int s)//模板
{
fill(ans + 1,ans + n + 1, -1e9);//因为是最长路,所以初始化为INT_MIN.
fill(vis + 1,vis + n + 1, 0);
fill(cnt + 1,cnt + n + 1, 0);
queue<int> q;
ans[s] = d;//起点也可以赚钱。
q.push(s);
while(q.size())
{
int u = q.front();
q.pop();
vis[u] = 0;
for(int i = 0;i < e[u].size(); ++ i)
{
int v = e[u][i].v , w = e[u][i].w;
if(ans[v] < ans[u] + d - w)//行驶费用为c,第i个城市赚钱数量为D。
{
ans[v] = ans[u] + d;
ans[v] -= w;
cnt[v] = cnt[u] + 1;
if(cnt[v] >= n)
{
return -1;//有正环
}
if(!vis[v])
{
q.push(v);
vis[v] = 1;
}
}
}
}
int ans1 = -1e9;
for(int i = 1;i <= n; ++ i)
{
ans1 = max(ans1 , ans[i]);
}
//在什么地点有最大值
return ans1;
}
AC代码:
#include <bits/stdc++.h>
using namespace std;
int d , m , n , m1 , s;
struct Node
{
int v , w;
};
const int N = 1e6 + 5;
vector<Node> e[N];
int ans[N],cnt[N],vis[N];
int spfa(int s)
{
fill(ans + 1,ans + n + 1, -1e9);
fill(vis + 1,vis + n + 1, 0);
fill(cnt + 1,cnt + n + 1, 0);
queue<int> q;
ans[s] = d;
q.push(s);
while(q.size())
{
int u = q.front();
q.pop();
vis[u] = 0;
for(int i = 0;i < e[u].size(); ++ i)
{
int v = e[u][i].v , w = e[u][i].w;
if(ans[v] < ans[u] + d - w)
{
ans[v] = ans[u] + d;
ans[v] -= w;
cnt[v] = cnt[u] + 1;
if(cnt[v] >= n)
{
return -1;
}
if(!vis[v])
{
q.push(v);
vis[v] = 1;
}
}
}
}
int ans1 = -1e9;
for(int i = 1;i <= n; ++ i)
{
ans1 = max(ans1 , ans[i]);
}
return ans1;
}
int main()
{
cin >> d >> m >> n >> m1 >> s;
for(int i = 1;i <= m; ++ i)
{
int u , v;
cin >> u >> v;
e[u].push_back({v , 0});//免费的边
}
for(int i = 1;i <= m1; ++ i)
{
int u , v , w ;
cin >> u >> v >> w;
e[u].push_back({v , w});//不免费的边
}
cout << spfa(s) << "\n";
return 0;
}