1219. 新红黑树
Constraints
Time Limit: 1 secs, Memory Limit: 32 MB
Description
A君和B君在玩一种叫做新红黑树的游戏,即在一棵由红枝和黑枝构成的树上轮流砍树枝,每次砍一枝,A君每次只能砍红枝,B君每次只能砍黑枝,当其中某人已经没有树枝砍的时候,由另外一人砍,直到砍完全部树枝。树枝是带权的,每个人的总分是他砍的树枝的权值之和,那些由于其他树枝被砍掉而与根失去联系的树枝会自动消失。每次由A君先砍,设“D=A君的得分-B君的得分”,A君想让D最大,而B君想让D最小,A君和B君都是极其聪明的人,他们始终以最优策略进行整个游戏,你知道最后的D值是多少吗?
Input
输入文件只有一组数据。第一行为一个整数N(1≤N≤20),表示树枝总数,以下N行每行有四个数a,b,c,w,分别为树枝的两个端点,颜色及权值,端点编号为0,1,...,N,0号节点为根结点,c=1表示红色,c=-1表示黑色,1<=w<=1000。
Output
输出文件包含一个整数,为所求的D值。
Sample Input
30 1 1 1001 2 -1 502 3 1 51
Sample Output
101
Problem Source
ZSUACM Team Member
// Problem#: 1219
// Submission#: 3587603
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <stdio.h>
const int INF = 2147483647;
const int MAXN = 21;
struct Tree {
int child, color, weight;
Tree * next;
} * tree[MAXN];
int n;
void search(int turn, int & value) {
Tree * tmp, * tmp1, *tmp2;
int f = 0, r = 1, l[MAXN];
int max = -INF, min = INF;
l[0] = 0;
while (f < r) {
tmp = tree[l[f++]];
while ((tmp1 = tmp->next) != NULL) {
l[r++] = tmp1->child;
if (tmp1->color == turn) {
tmp2 = tmp->next;
tmp->next = tmp1->next;
int ret = value + turn * tmp1->weight;
search(-turn, ret);
if (ret > max) max = ret;
if (ret < min) min = ret;
tmp->next = tmp2;
}
tmp = tmp1;
}
}
if (max == -INF || min == INF)
while (r--) value -= turn * tree[l[r]]->weight;
else
value = turn > 0 ? max : min;
}
int main() {
int i, a, b, c, w;
Tree * tmp;
scanf("%d", &n);
for (i = 0; i <= n; i++) {
tree[i] = new Tree;
tree[i]->next = NULL;
}
tree[0]->weight = 0;
for (i = 0; i < n; i++) {
scanf("%d%d%d%d", &a, &b, &c, &w);
tmp = tree[a]->next;
tree[a]->next = new Tree;
tree[a]->next->child = b;
tree[a]->next->color = c;
tree[a]->next->weight = w;
tree[a]->next->next = tmp;
tree[b]->weight = w;
}
int value = 0;
search(1, value);
printf("%d\n", value);
return 0;
}