Tallest Cow
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 3533 Accepted: 1658
Description
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.
Input
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.
Output
Lines 1…N: Line i contains the maximum possible height of cow i.
Sample Input
9 3 5 5
1 3
5 3
4 3
3 7
9 8
Sample Output
5
4
5
3
4
4
5
5
5
Source
USACO 2007 January Silver
分析
最直观的做法是,先把所有牛的高度置为H(最高的height),每次给出一对可以相互看见的牛,则把中间所有的牛高度减去1(因为这题身高为整数),这样就能得到最后的答案,但是时间复杂度很高。
换一种思路,记dh[i]为牛i的身高相对H的差值,即相对身高。记录这样一个数组ddh:ddh[i]=x意味着从i开始到数组末尾,dh的元素要加上x。那么,dh[i]实际上可以表示为
s
u
m
(
d
d
h
[
1...
i
]
)
sum(ddh[1...i])
sum(ddh[1...i]),即前缀和的形式。
d
h
[
(
a
+
1
)
.
.
.
(
b
−
1
)
]
dh[(a+1)...(b-1)]
dh[(a+1)...(b−1)]全部减去1,等价于
d
d
h
[
a
+
1
]
−
1
ddh[a+1]-1
ddh[a+1]−1,
d
d
h
[
b
]
+
1
ddh[b]+1
ddh[b]+1,最后要计算dh只需计算ddh的前缀和即可。这样就可以将O(n)的工作转变为O(1)的工作了。这便是差分计算的思想(百度百科链接:差分,差分计算)
代码
#include <iostream>
#include <algorithm>
#include <set>
#include <utility>
#define N 10002
using namespace std;
int main()
{
//有的编译器会把>>解释为一个整体,因此下面这种情况会报错
//所以还是写“>空格>”保险
set<pair<int, int> > can_see;
int n, tallest_i, tallest_h, r;
//h为height,dh为h的delta_h,ddh为delta_dh
int ddh[N] = {0};
int dh[N] = {0};
cin >> n >> tallest_i >> tallest_h >> r;
for(int i = 0; i < r; i++)
{
int a, b;
cin >> a >> b;
if(a > b)swap(a, b);
if(can_see.find(make_pair(a, b)) != can_see.end())continue;
ddh[a + 1]--, ddh[b]++;
can_see.insert(make_pair(a, b));
}
for(int i = 1; i <= n; i++)
{
dh[i] = dh[i - 1] + ddh[i];
cout << tallest_h + dh[i] << endl;
}
}