Minimal Ratio Tree 【HDU - 2489】【最优比例生成树+搜索】

题目链接


  刚看到这道题的时候,我相信很多读者会把它与二分答案的最优比例生成树联系在一起,当然,我也是这么想的,然而,后来怎么推也都没法合理的将它的优先队列的方程推导出来,所以想必是错了的。

  这道题还的确是用最优比例生成树,因为它的N、M偏小,最多也就是15,那么搜索就可行了,我们可以用dfs()去搜,每次将搜索的节点放进一个预存的数组中,然后当恰好搜到M个节点的时候,我们就对这M个节点去建立最优比例生成树,然后比较其与其他方案的大小就行了。


#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f
#define efs 1e-3
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
const int maxN=16;
int N, M;
double a[maxN], edge[maxN][maxN], lowercost[maxN], minn;
int need[maxN], ques[maxN];
double prime(int pos)
{
    double len=0;
    bool vis[maxN]; memset(vis, false, sizeof(vis));
    vis[pos]=true;
    for(int i=1; i<=M; i++)
    {
        lowercost[need[i]]=edge[need[pos]][need[i]];
    }
    for(int line=1; line<M; line++)
    {
        double tmp=INF;
        for(int i=1; i<=M; i++)
        {
            if(!vis[i] && tmp > lowercost[need[i]])
            {
                tmp = lowercost[need[i]];
                pos = i;
            }
        }
        vis[pos] = true;
        len += tmp;
        for(int i=1; i<=M; i++)
        {
            lowercost[need[i]]=min(lowercost[need[i]], edge[need[pos]][need[i]]);
        }
    }
    return len;
}
void dfs(int st, int cnt)
{
    if(cnt == M)
    {
        double need_node=0;
        for(int i=1; i<=M; i++) need_node += a[need[i]];
        double tmp = prime(1)/need_node;
        if(minn - tmp > efs)
        {
            minn = tmp;
            for(int i=1; i<=M; i++) ques[i] = need[i];
        }
    }
    else
    {
        for(int i=st+1; i<=N-M+cnt+1; i++)
        {
            need[cnt+1]=i;
            dfs(i, cnt+1);
        }
    }
}
int main()
{
    while(scanf("%d%d", &N, &M) && (N || M))
    {
        for(int i=1; i<=N; i++) scanf("%lf", &a[i]);
        for(int i=1; i<=N; i++) for(int j=1; j<=N; j++) scanf("%lf", &edge[i][j]);
        minn=INF;
        for(int i=1; i<=N-M+1; i++)
        {
            need[1]=i;
            dfs(i, 1);
        }
        for(int i=1; i<=M; i++) printf("%d%c", ques[i], i==M?'\n':' ' );
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wuliwuliii

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值