UVA10859 Placing Lampposts

Source

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1800

Solution

如果只考虑怎样使得放置的路灯数最小的话,这就是个大水题,只是那第二个条件有点烦人,要求被两个路灯覆盖的边数最小
这咋搞?
刘汝佳的书中给出了解决方案:
题目等价于被一条边覆盖的边数尽量少
那么现在就成了以路灯数为第一个关键字,被一个路灯覆盖的边数为第二关键字进行比较
一种显然的方式就是直接定义一个 c l a s s 然后重载一下小于号
第二种方式就是刘汝佳所说的,用 a M + b 表示这个值, M 很大,以至于 a 的影响远远大于 b 的影响,只有当 a 相等时 b 才会对答案有影响,这个题目中 a 就是路灯数, b 就是被一个路灯覆盖的边的条数

Code

//状压DP
#include <cstdio>
#include <algorithm>
#include <cstring>
#define maxn 1010
#define K 10000
#define clear(x) memset(x,0,sizeof(x))
using namespace std;
int n, m, f[maxn][2], head[maxn], nex[maxn<<1], tot, to[maxn<<1], vis[maxn], T;
void adde(int a, int b){to[++tot]=b;nex[tot]=head[a];head[a]=tot;}
void dfs(int pos)
{
    vis[pos]=1;
    f[pos][0]=0, f[pos][1]=K;
    for(int p=head[pos];p;p=nex[p])
        if(!vis[to[p]])
        {
            dfs(to[p]);
            f[pos][0]+=f[to[p]][1]+1;
            f[pos][1]+=min(f[to[p]][1],f[to[p]][0]+1);
        }
}
void input()
{
    tot=0;
    int i, a, b;
    scanf("%d%d",&n,&m);
    for(i=1;i<=m;i++)
    {
        scanf("%d%d",&a,&b);
        adde(a+1,b+1), adde(b+1,a+1);
    }
}
void solve()
{
    int i, A=0, B=0, C=0;
    for(i=1;i<=n;i++)
        if(!vis[i])
        {
            dfs(i);
            A+=min(f[i][0],f[i][1])/K;
            C+=min(f[i][0],f[i][1])%K;
        }
    B=m-C;
    printf("%d %d %d\n",A,B,C);
}
int main()
{
    int T;
    for(scanf("%d",&T);T--;)
    {
        clear(vis), clear(head), clear(nex), tot=0;
        input();
        solve();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/fsahfgsadhsakndas/article/details/81102418