【洛谷P2879】[USACO07JAN]Tallest Cow S

Tallest Cow S

问题描述

FJ's N (1 ≤ N ≤ 10,000) cows conveniently indexed 1..N are standing in a line. Each cow has a positive integer height (which is a bit of secret). You are told only the height H (1 ≤ H ≤ 1,000,000) of the tallest cow along with the index I of that cow.

FJ has made a list of R (0 ≤ R ≤ 10,000) lines of the form "cow 17 sees cow 34". This means that cow 34 is at least as tall as cow 17, and that every cow between 17 and 34 has a height that is strictly smaller than that of cow 17.

For each cow from 1..N, determine its maximum possible height, such that all of the information given is still correct. It is guaranteed that it is possible to satisfy all the constraints.

输入格式

Line 1: Four space-separated integers: N, I, H and R

Lines 2..R+1: Two distinct space-separated integers A and B (1 ≤ A, B ≤ N), indicating that cow A can see cow B.

输出格式

Lines 1..N: Line i contains the maximum possible height of cow i.

样例输入

9 3 5 5

1 3

5 3

4 3

3 7

9 8

样例输出

5

4

5

3

4

4

5

5

5

题解

牛的高度要尽量高,对于两头牛x,y,如果x能看见y,那么y的高度一定不小于x,如果没有其它限制,x和y的高度相等,因为若存在一种方案,使得x的高度小于y的高度,那么固定y的高度,显然存在一种更优的方案,即x的高度和y相等(事实上任何情况下x和y的高度都相等)

为了便于叙述,我们称站在x和y之间的牛为“中间牛”,要使得所有牛高度尽可能高,显然中间牛的高度为x和y的高度减一

最初在不知道任何看见关系的情况下,令所有牛的高度为最大高度

对于每一组x,y,将x,y所有中间牛的高度减一


由于高度是一个区间一个区间减的,可以保证x和y的高度相等

若x和y的高度不相等(假设x比y矮)

那么导致x比y矮的原因是x作为中间牛的次数比y多

即至少存在一组牛a,b,满足a<x<b<y,x是a,b的中间牛,而y不是,因此x就会比y矮

但同时b是x和y的中间牛,不可能比x高,所以这种情况不存在

所以x和y一定相等


由于整个算法只用到区间减,我们可以用差分数列优化时间

 

 

 1 #include <cstdio>
 2 #include <map>
 3 #define pa pair<int,int>
 4 using namespace std;
 5 int n,p,h,m,a[10005],s;
 6 map<pa,bool> mp;
 7 int main()
 8 {
 9     int i,j,x,y;
10     scanf("%d%d%d%d",&n,&p,&h,&m);
11     a[0]=h;
12     while (m--)
13     {
14         scanf("%d%d",&x,&y);
15         if (x>y) x^=y,y^=x,x^=y; 
16         if (mp[make_pair(x,y)]) continue;
17         mp[make_pair(x,y)]=1;
18         a[x+1]--;
19         a[y]++;
20     }
21     s=a[0];
22     for (i=1;i<=n;i++)
23     {
24         s=s+a[i];
25         printf("%d\n",s);
26     }
27     return 0;
28 }

 

posted @ 2021-10-22 23:56  SAKURA12  阅读(91)  评论(0编辑  收藏  举报