• POJ3904 Sky Code【容斥原理】


    题目链接:

    http://poj.org/problem?id=3904


    题目大意:

    给你N个整数。从这N个数中选择4个数,使得这四个数的公约数为1。求满足条件的

    四元组个数。


    解题思路:

    四个数的公约数为1。并不代表四个数两两互质。比方(2,3,4,5)公约数为1,可是

    2和4并不互质。

    从反面考虑。先求出四个数公约数不为1的情况个数,用总的方案个数

    减去四个数公约数不为1的情况个数就是所求。

    求四个数公约数不为1的情况个数,须要将N个数每一个数质因数分解,纪录下全部不同

    的素因子所能组成的因子(就是4个数的公约数),并统计构成每种因子的素因子个数。

    和因子总数。然后再计算组合数。

    比方说因子2的个数为a,则四个数公约数为2的个数

    为C(a。4)。因子3的个数为b。则四个数公约数为3的个数为C(b。4),因子6(2*3)的个

    为c,则四个数公约数的个数为C(c。4)。

    可是公约数为2的情况中或者公约数为3的情况中可能包含公约数为6的情况,相当于几

    集合求并集。这就须要容斥定理来做。详细參考代码。

    參考博文:http://blog.csdn.net/qiqijianglu/article/details/8009108


    AC代码:

    #include<iostream>
    #include<algorithm>
    #include<cstdio>
    #include<cstring>
    #include<cmath>
    #define LL __int64
    using namespace std;
    
    LL C(LL N) //计算 C(N,4)
    {
        return N * (N-1) * (N-2) * (N-3) / 24;
    }
    
    LL Factor[10010],ct,Count[10010],Num[10010];
    //Count[]纪录当前因子的个数,Num[]纪录当前因子是由几个素因子组成(用于容斥定理的奇加偶减)
    void Divide(LL N)   //将N分解质因数
    {
        ct = 0;
        for(int i = 2; i <= sqrt(N*1.0); ++i)
        {
            if(N % i == 0)
            {
                Factor[ct++] = i;
                while(N % i == 0)
                    N /= i;
            }
        }
        if(N != 1)
            Factor[ct++] = N;
    }
    
    void Solve(LL N)    //二进制实现容斥原理
    {
        Divide(N);
        for(int i = 1; i < (1 << ct); ++i)
        {
            LL tmp = 1;
            LL odd = 0;
            for(int j = 0; j < ct; ++j)
            {
                if((1 << j) & i)
                {
                    odd++;
                    tmp *= Factor[j];
                }
            }
            Count[tmp]++;
            Num[tmp] = odd;
        }
    }
    
    int main()
    {
        LL N,M;
        while(~scanf("%I64d",&N))
        {
            memset(Count,0,sizeof(Count));
            for(int i = 0; i < N; ++i)
            {
                scanf("%I64d",&M);
                Solve(M);
            }
            LL ans = 0;
            for(int i = 0; i <= 10000; ++i) //容斥
            {
                if(Count[i])
                {
                    if(Num[i] & 1)
                        ans += C(Count[i]);
                    else
                        ans -= C(Count[i]);
                }
            }
            printf("%I64d
    ",C(N) - ans);   //结果为C(N,4) - ans
        }
    
        return 0;
    }
    



  • 相关阅读:
    ios学习笔记——UIScrollView
    ios设计模式——单例模式
    ios设计模式——生成器模式
    ios学习笔记——UITableView
    ios 第3天
    ios 第2天
    ios入门第一天
    ios 运行时特征,动态改变控件字体大小
    ios 修改导航栏返回按钮的图片
    ios 在工程中使用字体
  • 原文地址:https://www.cnblogs.com/zhchoutai/p/7019250.html
Copyright © 2020-2023  润新知