MnZn求助差分约束
查看原帖
MnZn求助差分约束
930675
__xcm_楼主2023/10/20 14:48

在理解最短路和最长路的不同,所以两个都写了下,两种方法会分别 WA on #2 #4 求大佬指点一下。

#include<bits/stdc++.h>
#define ll long long
#define rep(i,a,b) for(int i = a;i <= b;i++)
#define per(i,a,b) for(int i = b;i >= a;i--)

using namespace std;
const int nn = 1e6+10;
const ll inf = 1e15;
struct node{ll v,w;};
vector<node> g[nn],e[nn];
int n,m;
ll min_dis[nn],max_dis[nn];
ll q[nn],st,ed;
ll vis[nn],cnt[nn];
ll S;
void spfa_max_dis()
{
	rep(i,0,n) max_dis[i] = -inf,vis[i] = cnt[i] = 0;max_dis[S] = 0; st = 1;ed = 0;q[++ed]	= S; vis[S] = 1; cnt[S]++;
	while(st <= ed)
	{
		int x = q[st++]; vis[x] = 0;
//		cout << x << "\n";
		for(auto it:g[x])
		{
			if(max_dis[it.v] < max_dis[x] + it.w)
			{
				max_dis[it.v] = max_dis[x] + it.w;
				if(!vis[it.v])
				{
					q[++ed] = it.v,vis[it.v] = 1;	
					if(++cnt[it.v] > n+1)
					{
					cout << "NO\n"; return;
					}
				}
				
			} 
		}
	}
	rep(i,1,n) cout << max_dis[i] << " "; cout << "\n";
}
void spfa_min_dis()
{
	rep(i,0,n) min_dis[i] = inf,vis[i] = cnt[i] = 0;min_dis[S] = 0; st = 1;ed = 0;q[++ed]= S; vis[S] = 1;cnt[S]++;
	while(st <= ed)
	{
		int x = q[st++]; vis[x] = 0;
//		cout << x << "\n";
		for(auto it:e[x])
		{
			if(min_dis[it.v] > min_dis[x] + it.w)
			{
				min_dis[it.v] = min_dis[x] + it.w;
				if(!vis[it.v])
				{
					q[++ed] = it.v,vis[it.v] = 1;
					if(++cnt[it.v] > n+1)
					{	
					cout << "NO\n"; return;
					}
				}
			} 
		}
	}
	rep(i,1,n) cout << min_dis[i] << " "; cout << "\n";
}
void mian()
{
	cin >> n >> m;	ll x,y,z;
	rep(i,1,m) cin >> x >> y >> z,g[x].push_back({y,-z}),e[y].push_back({x,z});
	rep(i,1,n) g[S].push_back({i,0}),e[S].push_back({i,0});
	spfa_max_dis();
	spfa_min_dis(); 
}

int main()
{
	ios::sync_with_stdio(0);cin.tie(0);
	mian();
	return 0;
}

2023/10/20 14:48
加载中...