1. 程式人生 > >小K的農場(luogu P1993

小K的農場(luogu P1993

n) #define ref sizeof amp set code ora AC

題目傳送門

題目描述

小K在MC裏面建立很多很多的農場,總共n個,以至於他自己都忘記了每個農場中種植作物的具體數量了,他只記得一些含糊的信息(共m個),以下列三種形式描述:

  • 農場a比農場b至少多種植了c個單位的作物,
  • 農場a比農場b至多多種植了c個單位的作物,
  • 農場a與農場b種植的作物數一樣多。

但是,由於小K的記憶有些偏差,所以他想要知道存不存在一種情況,使得農場的種植作物數量與他記憶中的所有信息吻合。

輸入輸出格式

輸入格式:

第一行包括兩個整數 n 和 m,分別表示農場數目和小 K 記憶中的信息數目。

接下來 m 行:

如果每行的第一個數是 1,接下來有 3 個整數 a,b,c,表示農場 a 比農場 b 至少多種植

了 c 個單位的作物。

如果每行的第一個數是 2,接下來有 3 個整數 a,b,c,表示農場 a 比農場 b 至多多種植

了 c 個單位的作物。如果每行的第一個數是 3,家下來有 2 個整數 a,b,表示農場 a 終止的

數量和 b 一樣多。

輸出格式:

如果存在某種情況與小 K 的記憶吻合,輸出“Yes”,否則輸出“No”。

輸入輸出樣例

輸入樣例#1:
3 3
3 1 2
1 1 3 1
2 2 3 2
輸出樣例#1:
Yes

說明

對於 100% 的數據保證:1 ≤ n,m,a,b,c ≤ 10000。

  差分約束求可行解。判負環的時候spfa用stack代替queue會快很多。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<cmath>
 6 #include<queue>
 7 #include<stack>
 8
#include<bitset> 9 #define LL long long 10 #define RI register int 11 using namespace std; 12 const int INF = 0x7ffffff ; 13 const int N = 10000 + 10 ; 14 15 inline int read() { 16 int k = 0 , f = 1 ; char c = getchar() ; 17 for( ; !isdigit(c) ; c = getchar()) 18 if(c == -) f = -1 ; 19 for( ; isdigit(c) ; c = getchar()) 20 k = k*10 + c-0 ; 21 return k*f ; 22 } 23 struct Edge { 24 int to, next, val ; 25 }e[N<<1] ; 26 int n, m ; int head[N], dis[N], num[N] ; 27 inline void add_edge(int x,int y,int z) { 28 static int cnt = 0 ; 29 e[++cnt].to = y, e[cnt].next = head[x], head[x] = cnt, e[cnt].val = z ; 30 } 31 32 inline bool spfa() { 33 memset(dis,127,sizeof(dis)) ; dis[0] = 0 ; 34 stack<int>s ; s.push(0) ; bitset<N>ins ; ins[0] = 1 ; 35 while(!s.empty()) { 36 int x = s.top() ; s.pop() ; num[x]++ ; if(num[x] > n) return 0 ; 37 for(int i=head[x];i;i=e[i].next) { 38 int y = e[i].to ; 39 if(dis[y] > dis[x]+e[i].val) { 40 dis[y] = dis[x]+e[i].val ; 41 if(!ins[y]) { 42 s.push(y) ; ins[y] = 1 ; 43 } 44 } 45 } 46 ins[x] = 0 ; 47 } 48 return 1 ; 49 } 50 51 int main() { 52 n = read(), m = read() ; 53 while(m--) { 54 int ii = read() ; 55 if(ii == 1) { 56 int x = read(), y = read(), z = read() ; 57 add_edge(y,x,-z) ; 58 } else if(ii == 2) { 59 int x = read(), y = read(), z = read() ; 60 add_edge(x,y,z) ; 61 } else { 62 int x = read(), y = read() ; 63 add_edge(y,x,0), add_edge(x,y,0) ; 64 } 65 } 66 for(int i=1;i<=n;i++) add_edge(0,i,0) ; 67 if(spfa()) printf("Yes") ; 68 else printf("No") ; 69 return 0 ; 70 }

小K的農場(luogu P1993