[HDU - 2489]Minimal Ratio Tree

题意:输入n个点,要求选m个点满足连接m个点的m-1条边权值和sum与点的权值和ans最小,即sum/ans最小,并输出所选的m个点,如果有多种情况就选第一个点最小的,如果第一个点也相同就选第二个点最小的........
分析:因为n<=15,所以可以暴力枚举出所选的m个点,然后对这m个点进行最小生成树求得m-1条边的最小和,然后求sum/ans即可

#include <cstdio>
#include <cstring>
#define maxn 15 + 5
#define inf 0x3f3f3f3f
int graph[maxn][maxn], vex[maxn];
int n, m, store[maxn], vis[maxn];
double ans;
bool visted[maxn];

double prim()
{
    int minid, cnt = 0, mcost, n_vex = 0, n_edge = 0;
    for (int i = 1; i <= m; ++i)
        n_vex += vex[vis[i]];
    memset(visted, 0, sizeof(visted));
    visted[1] = 1;
    while (cnt < m - 1)
    { 
        mcost = inf;
        for (int i = 1; i <= m; ++i)
        {
            if (!visted[i])
                continue;
            for (int j = 1; j <= m; ++j)
                if (!visted[j] && graph[vis[i]][vis[j]] < mcost)
                {
                    mcost = graph[vis[i]][vis[j]];
                    minid = j;
                }
        }
        if (mcost != inf)
        {
            visted[minid] = 1;
            n_edge += mcost;
            ++cnt;
        }
    }
    return n_edge * 1.0 / n_vex;
}

void dfs(int k, int id)
{
    if(id > m){
        double mcost = prim();
        if(mcost - ans < -(1e-8)) //!!!!
        {
            ans = mcost; 
            memcpy(store, vis, sizeof(vis));
        } 
        return;
    }
    for (int i = k; i <= n; ++i)
    {
        vis[id] = i;
        dfs(i + 1, id + 1);
    }
}

int main()
{
    while (~scanf("%d %d", &n, &m) && (n || m))
    {
        for (int i = 1; i <= n; ++i)
            scanf("%d", &vex[i]);
        for (int i = 1; i <= n; ++i)
            for (int j = 1; j <= n; ++j)
                scanf("%d", &graph[i][j]);
        ans = inf;
        dfs(1, 1);
        for (int i = 1; i <= m; ++i)
            if (i != m)
                printf("%d ", store[i]);
            else
                printf("%d\n", store[i]);
    }
    return 0;
}

 

上一篇:sum(),max(),avg(),RATIO_TO_REPORT()--分组统计


下一篇:进度条