題目描述
Farmer John has decided to assemble a panoramic photo of a lineup of his N cows (1 <= N <= 200,000), which, as always, are conveniently numbered from 1..N. Accordingly, he snapped M (1 <= M <= 100,000) photos, each covering a contiguous range of cows: photo i contains cows a_i through b_i inclusive. The photos collectively may not necessarily cover every single cow.ios
After taking his photos, FJ notices a very interesting phenomenon: each photo he took contains exactly one cow with spots! FJ was aware that he had some number of spotted cows in his herd, but he had never actually counted them. Based on his photos, please determine the maximum possible number of spotted cows that could exist in his herd. Output -1 if there is no possible assignment of spots to cows consistent with FJ's photographic results.app
農夫約翰決定給站在一條線上的N(1 <= N <= 200,000)頭奶牛製做一張全家福照片,N頭奶牛編號1到N。ide
因而約翰拍攝了M(1 <= M <= 100,000)張照片,每張照片都覆蓋了連續一段奶牛:第i張照片中包含了編號a_i 到 b_i的奶牛。可是這些照片不必定把每一隻奶牛都拍了進去。優化
在拍完照片後,約翰發現了一個有趣的事情:每張照片中都有且僅有一隻身上帶有斑點的奶牛。約翰意識到他的牛羣中有一些斑點奶牛,但他歷來沒有統計過它們的數量。 根據照片,請你幫約翰估算在他的牛羣中最多可能有多少隻斑點奶牛。若是無解,輸出「-1」。spa
Inputrest
輸入輸出格式
輸入格式:code
* Line 1: Two integers N and M.blog
* Lines 2..M+1: Line i+1 contains a_i and b_i.隊列
輸出格式:ci
* Line 1: The maximum possible number of spotted cows on FJ's farm, or -1 if there is no possible solution.
輸入輸出樣例
說明
There are 5 cows and 3 photos. The first photo contains cows 1 through 4, etc.
From the last photo, we know that either cow 3 or cow 4 must be spotted. By choosing either of these, we satisfy the first two photos as well.
題解
- 真的是卡spfa卡的不亦樂乎!
- 題目大意:給定n個區間,每一個區間中只有一頭斑點牛,求最多可能有多少頭斑點牛
- 每一個區間最少只有一頭斑點牛,也最多隻有一頭斑點牛
- 那麼一隻奶牛要不就是斑點牛,要不就是正常牛,那麼就是0<=sum[i]-sum[i-1]<=1
- 轉移一下sum[R]-sum[L-1]<=1,sum[L-1]-sum[R]<=-1
- 那麼就能夠差分約束,把i和i-1之間連一條0邊,i-1和i之間連一條1邊,a-1和b之間連一條1邊,b和a-1之間連一條-1邊
- 如何跑一個優秀的spfa纔是重點,能夠用雙向隊列優化spfa
代碼
1 #include <cstdio> 2 #include <iostream> 3 #include <queue> 4 #define N 200010 5 #define inf 0x7fffffff 6 using namespace std; 7 struct edge {int to,from,v;}e[N*4]; 8 int n,m,vis[N*2],dis[N*2],head[N*2],cnt=1,tot; 9 void insert(int x,int y,int v) { e[++cnt].to=y,e[cnt].from=head[x],e[cnt].v=v,head[x]=cnt; } 10 int spfa() 11 { 12 deque<int> Q; 13 for (int i=1;i<=n;i++) dis[i]=inf; 14 vis[0]=1,Q.push_back(0); 15 while (Q.size()) 16 { 17 int u=Q.front(); Q.pop_front(),vis[u]=0; 18 for (int i=head[u];i;i=e[i].from) 19 if (dis[e[i].to]>dis[u]+e[i].v) 20 { 21 dis[e[i].to]=dis[u]+e[i].v; 22 if (!vis[e[i].to]) 23 { 24 if (++tot>1926817) return -1; 25 vis[e[i].to]=1; 26 if (Q.size()&&dis[e[i].to]>dis[Q.front()]) Q.push_back(e[i].to); else Q.push_front(e[i].to); 27 } 28 } 29 } 30 return dis[n]; 31 } 32 int main() 33 { 34 scanf("%d%d",&n,&m); 35 for (int i=1,l,r;i<=m;i++) scanf("%d%d",&l,&r),insert(l-1,r,1),insert(r,l-1,-1); 36 for (int i=1;i<=n;i++) insert(i-1,i,1),insert(i,i-1,0); 37 printf("%d\n",spfa()); 38 }