POJ3263 Tallest Cow 題解 差分陣列
阿新 • • 發佈:2020-09-04
題目連結:http://poj.org/problem?id=3263
題目大意:有 \(N\) 頭牛,最高的是第 \(I\) 頭,身高是 \(H\) ,現在有 \(R\) 組相對關係。每組相對關係有兩個數 \(A\) 和 \(B\),表示 \(A\) 和 \(B\) 能相互看見,也就是他們中間的牛都比他倆矮。輸出所有牛的最大的可能身高。
解題思路:
\(A\) 和 \(B\) 可以相互看見,其實就是 \([A+1,B-1]\) 區間的牛都比他倆低,也就是我們把這個區間的值都減去 \(1\) 即可。
定義一個差分陣列 \(d\),令 \(d[A+1] -= 1, d[B] += 1\) 即可。
坑點
示例程式碼如下:
#include <cstdio> #include <cstring> #include <algorithm> #include <set> using namespace std; const int maxn = 10010; int n, I, H, R, a, b, h[maxn], d[maxn]; // d[]差分陣列 set<pair<int, int> > st; int main() { while (~scanf("%d%d%d%d", &n, &I, &H, &R)) { memset(h, 0, sizeof(int)*(n+1)); while (R --) { scanf("%d%d", &a, &b); if (a > b) swap(a, b); if (st.count(make_pair(a, b))) continue; st.insert(make_pair(a, b)); d[a+1] --; d[b] ++; } for (int i = 1; i <= n; i ++) h[i] = h[i-1] + d[i]; for (int i = 1; i <= n; i ++) { printf("%d\n", h[i] + H - h[I]); } } return 0; }