HDU_2489
由于N很小,可以枚举保留的顶点的情况并依次计算最小生成树,然后更新一下记录的结果即可。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAXD 20
#define MAXM 400
int N, M, u[MAXM], v[MAXM], w[MAXM], vis[MAXD], r[MAXM], node[MAXD], p[MAXD], e, wa[MAXD], wb[MAXD], *a, *b, ew, nw;
int cmp(const void *_p, const void *_q)
{
int *p = (int *)_p, *q = (int *)_q;
return w[*p] - w[*q];
}
int find(int x)
{
return p[x] == x ? x : (p[x] = find(p[x]));
}
void init()
{
int i, j, k;
for(i = 0; i < N; i ++)
scanf("%d", &node[i]);
e = 0;
for(i = 0; i < N; i ++)
for(j = 0; j < N; j ++)
{
u[e] = i, v[e] = j;
scanf("%d", &k);
if(i != j)
w[e ++] = k;
}
}
void update()
{
int i, *c;
for(i = 0; i < M; i ++)
{
if(a[i] < b[i])
return ;
else if(a[i] > b[i])
{
c = a, a = b, b = c;
return ;
}
}
}
void getans()
{
int i, j, k, x, y, t1, t2, *c;
t1 = t2 = 0;
for(i = 0; i < N; i ++)
p[i] = i;
for(i = 0; i < e; i ++)
{
k = r[i];
if(!vis[u[k]] && !vis[v[k]])
{
x = find(u[k]), y = find(v[k]);
if(x != y)
{
t1 += w[k];
p[x] = y;
}
}
}
for(i = 0; i < M; i ++)
t2 += node[b[i]];
if(ew < 0 || t1 * nw < t2 * ew)
{
ew = t1, nw = t2;
c = a, a = b, b = c;
}
else if(t1 * nw == t2 * ew)
update();
}
void solve()
{
int i, j, k, t;
a = wa, b = wb, ew = -1;
for(i = 0; i < e; i ++)
r[i] = i;
qsort(r, e, sizeof(r[0]), cmp);
for(k = 0; k < (1 << N); k ++)
{
t = 0;
for(i = 0; i < N; i ++)
{
if((1 << i) & k)
{
vis[i] = 0;
b[t] = i;
++ t;
}
else
vis[i] = 1;
}
if(t == M)
getans();
}
printf("%d", a[0] + 1);
for(i = 1; i < M; i ++)
printf(" %d", a[i] + 1);
printf("\n");
}
int main()
{
for(;;)
{
scanf("%d%d", &N, &M);
if(!N && !M)
break;
init();
solve();
}
return 0;
}