您的位置:首页 > 其它

HDU5242.Game——贪心

2015-05-31 11:57 363 查看
http://acm.hdu.edu.cn/showproblem.php?pid=5242

一棵树有n个结点,n-1条边,每个结点有个权值。每次可以获得从根节点走到叶子结点所有结点的权值和,但是每个结点的权值只能使用一次。求走k次所能获得的最大权值和

dfs1求出所有结点到根节点的权值和,然后按从大到小排序,根据这个顺序,dfs2求出每个结点到根节点的权值和,遍历过的结点的权值不能用。

然后再从大到小排个序,取前面的k个

每次选择一个叶子结点走到根节点,相当于每次取一条单链,对于有交叉的两条链,先选权值大的肯定是最优的,因为对于某条跟它们没有交叉的链来说,这样子的操作并不会影响到它

[code]#include <bits/stdc++.h>
#define clr(a,b) memset(a,b,sizeof(a))
const int maxn = 100010;
using namespace std;
typedef long long LL;
int n,m;
LL a[maxn],x[maxn];
bool vis[maxn];
struct Edge{
    int to,next;
}edge[maxn<<1];int head[maxn],tot;
void init()
{
    tot=0;
    clr(head,0xff);
}
void addedge(int u,int v)
{
    edge[tot].to=v;
    edge[tot].next=head[u];
    head[u]=tot++;
}
struct Node{
    LL sum;
    int id;
    bool operator<(const Node&a)const{
        return sum>a.sum;
    }
}node[maxn];
LL dfs1(int u)
{
    if(vis[u]) return node[u].sum;
    node[u].sum=a[u];
    vis[u]=true;
    for(int i=head[u];~i;i=edge[i].next){
        int v=edge[i].to;
        node[u].sum+=dfs1(v);
    }
    return node[u].sum;
}
LL dfs2(int u)
{
    if(vis[u]) return 0;
    LL w=a[u];
    vis[u]=true;
    for(int i=head[u];~i;i=edge[i].next){
        int v=edge[i].to;
        w+=dfs2(v);
    }
    return w;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif // ONLINE_JUDGE
    int T,cas=1;
    scanf("%d",&T);
    while(T--){
        scanf("%d%d",&n,&m);
        clr(node,0);
        for(int i=1;i<=n;++i){
            scanf("%I64d",&a[i]);
            node[i].id=i;
        }
        clr(vis,false);
        init();
        int u,v;
        for(int i=1;i<n;++i){
            scanf("%d%d",&u,&v);
            addedge(v,u);
        }
        for(int i=1;i<=n;++i){
            if(!vis[i]){
                dfs1(i);
            }
        }
//        cout<<"-----"<<endl;
        sort(node+1,node+n+1);
        clr(vis,false);
        for(int i=1;i<=n;++i){
            x[i]=dfs2(node[i].id);
        }

        LL ans=0;
        sort(x+1,x+n+1,greater<LL>());
//        for(int i=1;i<=n;++i) cout<<x[i]<<" ";cout<<endl;
        for(int i=1,cnt=0;i<=n,cnt<m;++i)
            ans+=x[i],cnt++;
        printf("Case #%d: %I64d\n",cas++,ans);
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: