Sicily 1219. 新红黑树

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;
}                                 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值