HDU 4583 Coffee shop in Jioufen 解题报告(DFS+剪枝)

    题目大意:给定n个数的序列,问互质的序列有多少个。

    解题报告:在我写这篇解题报告之前,我搜了N久都搜不到解题报告。如果你也是这样感觉自己不会做,超时,或者WA了,跟自己说声,Try again!因为总会有没有解题报告的一天!!!还是希望你自己能再想一次,再试一次,再测个样例。自己想出来A掉题目才会有真正的快乐。

    这题没有想象中那么难。很普通的DFS+剪枝就可以搞定了。但是2^60可不是开玩笑,给了5秒,还是会TLE……剪枝是关键。

    先贴个测试数据,如果你的代码是TLE的,下面的数据应该可以测出来:

    60

    2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113

    2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113

    也就是前30个素数,每个素数出现两次。

    我的代码跑出来的结果是:205891132094649

    如果你的代码非常慢,就根据这个数据考虑怎么剪枝吧。

    


    贴个代码,HDU上1343MS,62MS的……太夸张了= =

#include <iostream>
#include <cstdio>
#include <bitset>
#include <algorithm>
using namespace std;

#define LL long long
#define Bool bitset<maxn>

const int maxn=60;
int a[maxn];
Bool to[maxn];
LL num[maxn];
LL ans;

bool gcd(int a,int b)
{
	return b==0?a!=1:gcd(b,a%b);
}

LL DFS(int n,Bool p)
{
	if(n==-1)
		return 1;
	LL res=DFS(n-1,p);
	if(p.test(n))
		return res;
	if((p|to[n])==p)
		return res*num[n];
	else
		return res+DFS(n-1,(p|to[n]))*(num[n]-1);
}

int main()
{
	int n;
	while(~scanf("%d",&n) && n)
	{
		for(int i=0;i<n;i++)
			scanf("%d",a+i);
		sort(a,a+n);

		int m=0;
		num[0]=2;
		for(int i=1;i<n;i++)
		{
			if(a[i]==a[m])
				num[m]++;
			else
			{
				a[++m]=a[i];
				num[m]=2;
			}
		}

		for(int i=0;i<=m;i++)
		{
			to[i].reset();
			for(int j=0;j<i;j++)
				if(gcd(a[j],a[i]))
					to[i].set(j);
		}

		ans=0;
		Bool p;
		printf("%I64d\n",DFS(m,p));
	}
}

   使用long long代替bitset也是可以的,而且快一点。代码如下,时间904MS:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;

#define LL long long

const int maxn=60;
int a[maxn];
LL to[maxn];
int num[maxn];
LL ans;

bool gcd(int a,int b)
{
    return b==0?a!=1:gcd(b,a%b);
}

LL DFS(int n,LL p)
{
    if(n==-1)
        return 1;
    LL res=DFS(n-1,p);
    if(p&(1LL<<n))
        return res;
    if((p|to[n])==p)
        return res*num[n];
    else
        return res+DFS(n-1,(p|to[n]))*(num[n]-1);
}

int main()
{
    int n;
    while(~scanf("%d",&n) && n)
    {
        for(int i=0;i<n;i++)
            scanf("%d",a+i);
        sort(a,a+n);

        int m=0;
        num[0]=2;
        for(int i=1;i<n;i++)
        {
            if(a[i]==a[m])
                num[m]++;
            else
            {
                a[++m]=a[i];
                num[m]=2;
            }
        }

        memset(to,0,sizeof(to));
        for(int i=0;i<=m;i++)
        {
            for(int j=0;j<i;j++)
                if(gcd(a[j],a[i]))
                    to[i]|=1LL<<j;
        }

        ans=0;
        printf("%I64d\n",DFS(m,0));
    }
}


   这是我第一次被没有解题报告逼出来,自己最终A掉的题目,好好纪念下。SF-_-

    转载就留个地址吧:http://blog.csdn.net/sf____/article/details/10026297

你可能感兴趣的:(DFS)