BZOJ 1691: [Usaco2007 Dec]挑剔的美食家( 平衡树 )

按鲜嫩程度排个序, 从大到小处理, 用平衡树维护价值 

----------------------------------------------------------------------

#include<bits/stdc++.h>
 
using namespace std;
 
typedef long long ll;
 
const int maxn = 100009;
const int INF = 2000000000;
 
struct cow {
int w, v;
void Read() {
scanf("%d%d", &w, &v);
}
bool operator < (const cow &o) const {
return v > o.v;
}
} A[maxn];
 
struct O {
int w, v;
void Read() {
scanf("%d%d", &w, &v);
}
bool operator < (const O &o) const {
return v > o.v;
}
} B[maxn];
 
int N, M;
 
struct Node {
Node* ch[2];
int v, s, r;
} pool[maxn], *pt = pool, *null, *root;
 
void init() {
null = pt++;
null->ch[0] = null->ch[1] = null;
null->v = null->s = 0;
}
 
Node* newNode(int v) {
pt->v = v; pt->s = 1; pt->r = rand(); pt->ch[0] = pt->ch[1] = null; return pt++;
}
 
void Rotate(Node* &t, int d) {
Node* o = t->ch[d ^ 1];
t->ch[d ^ 1] = o->ch[d];
o->ch[d] = t;
t = o;
}
 
void Insert(Node* &t, int v) {
if(t == null)
t = newNode(v);
else {
int d = (t->v < v);
Insert(t->ch[d], v);
if(t->ch[d]->r > t->r) Rotate(t, d ^ 1);
}
}
 
void Delete(Node* &t, int v) {
int d = (t->v != v ? (t->v < v) : -1);
if(d == -1) {
if(t->ch[0] != null && t->ch[1] != null) {
int d = (t->ch[0]->r > t->ch[1]->r);
Rotate(t, d); Delete(t->ch[d], v);
} else
t = (t->ch[0] != null ? t->ch[0] : t->ch[1]);
} else 
Delete(t->ch[d], v);
}
 
int succ(int v) {
int ret = INF;
for(Node* t = root; t != null;)
if(t->v >= v) 
ret = min(ret, t->v), t = t->ch[0];
else
t = t->ch[1];
return ret;
}
 
int main() {
init(); root = null;
scanf("%d%d", &N, &M);
for(int i = 0; i < N; i++) A[i].Read();
for(int i = 0; i < M; i++) B[i].Read();
sort(A, A + N); sort(B, B + M);
int p = 0; ll ans = 0;
for(int i = 0; i < N; i++) {
while(p < M && B[p].v >= A[i].v)
Insert(root, B[p++].w);
int t = succ(A[i].w);
Delete(root, t);
ans += t;
}
printf("%lld\n", ans);
return 0;
}

----------------------------------------------------------------------

1691: [Usaco2007 Dec]挑剔的美食家

Time Limit: 5 Sec  Memory Limit: 64 MB
Submit: 585  Solved: 261
[Submit][Status][Discuss]

Description

与很多奶牛一样,Farmer John那群养尊处优的奶牛们对食物越来越挑剔,随便拿堆草就能打发她们午饭的日子自然是一去不返了。现在,Farmer John不得不去牧草专供商那里购买大量美味多汁的牧草,来满足他那N(1 <= N <= 100,000)头挑剔的奶牛。 所有奶牛都对FJ提出了她对牧草的要求:第i头奶牛要求她的食物每份的价钱不低于A_i(1 <= A_i <= 1,000,000,000),并且鲜嫩程度不能低于B_i(1 <= B_i <= 1,000,000,000)。商店里供应M(1 <= M <= 100,000)种不同的牧草,第i 种牧草的定价为C_i(1 <= C_i <= 1,000,000,000),鲜嫩程度为D_i (1 <= D_i <= 1,000,000,000)。 为了显示她们的与众不同,每头奶牛都要求她的食物是独一无二的,也就是说,没有哪两头奶牛会选择同一种食物。 Farmer John想知道,为了让所有奶牛满意,他最少得在购买食物上花多少钱。

Input

* 第1行: 2个用空格隔开的整数:N 和 M

* 第2..N+1行: 第i+1行包含2个用空格隔开的整数:A_i、B_i * 第N+2..N+M+1行: 第j+N+1行包含2个用空格隔开的整数:C_i、D_i

Output

* 第1行: 输出1个整数,表示使所有奶牛满意的最小花费。如果无论如何都无法 满足所有奶牛的需求,输出-1

Sample Input

4 7
1 1
2 3
1 4
4 2
3 2
2 1
4 3
5 2
5 4
2 6
4 4

Sample Output

12

输出说明:

给奶牛1吃价钱为2的2号牧草,奶牛2吃价钱为4的3号牧草,奶牛3分到价钱
为2的6号牧草,奶牛4选择价钱为4的7号牧草,这种分配方案的总花费是12,为
所有方案中花费最少的。

HINT

Source

 

posted @ 2015-10-15 22:01  JSZX11556  阅读(225)  评论(0编辑  收藏  举报