1. 程式人生 > >蒜頭君當大廚【差分約束板子】

蒜頭君當大廚【差分約束板子】

問題描述

蒜頭君苦練廚藝,終於成為了某高檔酒店的大廚。 每天上班,蒜頭君會被要求做 nnn 份菜。既然是高檔酒店,那麼客人們當然是很講究的,尤其對於上菜的時間有很多要求。客人們的要求被分成下列四種: 菜品 a 的上菜時間必須比菜品 b的上菜時間早 d 分鐘或者更早。 菜品 a的上菜時間必須比菜品 b的上菜時間遲 d分鐘或者更遲。 菜品 a 的上菜時間在 d 分鐘以後(包含 d 分鐘)。 菜品 a 的上菜時間在 d 分鐘之前(包含 d 分鐘)。 蒜頭君的上班時間記為 0 分鐘。為了節約時間,在滿足客人們要求的情況下,蒜頭君希望最後上的一道菜的時間儘可能的早。(每道菜的上菜時間必須不早於蒜頭君的上班時間)

輸入格式

第一行輸入一個整數 n,表示一共需要上 n 道菜。 第二行輸入一個整數 m,表示客人們的要求數量。 接下里 m 行,每行先輸入一個整數 op。 如果 op=1,表示描述裡的第 1 種要求,後面跟著三個整數 a,b,d; 如果 op=2,表示描述裡的第 2 種要求,後面跟著三個整數 a,b,d; 如果 op=3,表示描述裡的第 3 種要求,後面跟著兩個整數 a,d; 如果 op=4,表示描述裡的第 4 種要求,後面跟著兩個整數 a,d。

輸出格式

能滿足客人們的要求,輸出最後一道菜的上菜時間;否則輸出一行 I can’t。

#include <cmath>
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define ll long long
#define rep(i,x,y) for(ll i=(x);i<=(y);i++)
#define repl(i,x,y) for(ll i=(x);i<(y);i++)
#define repd(i,x,y) for(ll i=(x);i>=(y);i--)
using namespace std;

const ll N=2e5+5;
const ll Inf=1e18;

ll n,m,ans,flag,dis[N],vis[N],tot[N];
ll cnt,to[N],edge[N],nxt[N],head[N];

inline ll read() {
	ll x=0;char ch=getchar();bool f=0;
	while(ch>'9'||ch<'0'){if(ch=='-')f=1;ch=getchar();}
	while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}
	return f?-x:x;
}

void ins(ll x,ll y,ll z) {
	to[++cnt]=y;edge[cnt]=z;nxt[cnt]=head[x];head[x]=cnt;
}

void spfa(ll s) {
	rep(i,1,n) vis[i]=0,dis[i]=-1;
	queue<ll>q;q.push(s);vis[s]=1;dis[s]=0;
	
	while(q.size()) {
		ll x=q.front();q.pop();vis[x]=0;
		
		for(ll i=head[x];i;i=nxt[i]) {
			ll y=to[i],z=edge[i];
			
			if(dis[x]+z>dis[y]) {
				dis[y]=dis[x]+z;
				if(!vis[y]) {
					vis[y]=1;q.push(y);
					if(++tot[y]==n+1) {
						flag=1;return ;
					}
				}
			}
		}
	}
}

int main() {
	n=read(),m=read();

	rep(i,1,m) {
		ll type=read();
		
		if(type==1) {
			ll x=read(),y=read(),z=read();ins(x,y,z);
		} else if (type==2) {
			ll x=read(),y=read(),z=read();ins(y,x,z);
		} else if (type==3) {
			ll x=read(),z=read();ins(0,x,z);
		} else {
			ll x=read(),z=read();ins(x,0,-z);
		}
	}
	
	rep(i,1,n) ins(0,i,0);
	
	spfa(0);
	if(flag) printf("I can't\n");
	else {
		rep(i,1,n) ans=max(ans,dis[i]);
	
		printf("%lld\n",ans);
	}
	
	return 0;
}