双亲数 容斥

小D是一名数学爱好者,他对数字的着迷到了疯狂的程度。
我们以d = gcd(a, b)表示a、b的最大公约数,小D执著的认为,这样亲密的关系足可以用双亲来描述,此时,我们称有序数对(a, b)为d的双亲数。
与正常双亲不太相同的是,对于同一个d,他的双亲太多了 >_<
比如:(4, 6), (6, 4), (2, 100)都是2的双亲数。
于是一个这样的问题摆在眼前,对于0 < a <= A, 0 < b <= B,有多少有序数对(a, b)是d的双亲数?

 

题意就是求满足0<x<=N,0<y<=M,gcd(x,y)=d的点对数量;

设f[i]为gcd(x,y)=i的点对数量,根据乘法原理可得满足i|gcd(x,y)的点对数量为(n/i)*(m/i),我们只需要将后面的数量减去sum(f[d*i]),d>=2,d*i<=min(n,m);

这就是个从后向前的递推,时间复杂度是O(nlogn);

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cstdlib>
#include<ctime>
#include<vector>
#include<algorithm>
#include<queue>
#include<map>
using namespace std;
#define LL long long
int n,m,d;
LL f[1010000];
void init(){
    scanf("%d%d%d",&n,&m,&d);
    LL sum=0;
    if(n>m)swap(n,m);
    for(int i=n/d*d;i;i-=d){
        f[i]=((LL)n/i)*((LL)m/i);
        for(int j=i<<1;j<=n;j+=i)f[i]-=f[j];
    }
    cout<<f[d]<<endl;
    
}
int main(){
    freopen("1.in","r",stdin);
    freopen("1.out","w",stdout);
    init();
    return 0;
}

 

转载于:https://www.cnblogs.com/chadinblog/p/5879747.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
二叉树的双亲节点是指除了根节点之外,每一个节点都有一个父节点。二叉树的叶子节点是指没有子节点的节点。因此,求二叉树的双亲节点个数和叶子节点个数可以通过遍历二叉树来实现。 以下是求二叉树双亲节点个数和叶子节点个数的程序实现: ```c #include <stdio.h> #include <stdlib.h> // 定义二叉树节点结构体 typedef struct TreeNode { int val; struct TreeNode* left; struct TreeNode* right; } TreeNode; // 创建二叉树 TreeNode* createTree() { int val; scanf("%d", &val); if (val == -1) { return NULL; } TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode)); root->val = val; root->left = createTree(); root->right = createTree(); return root; } // 计算二叉树双亲节点个数和叶子节点个数 void countNodes(TreeNode* root, int* parentCount, int* leafCount) { if (root == NULL) { return; } if (root->left != NULL || root->right != NULL) { (*parentCount)++; } else { (*leafCount)++; } countNodes(root->left, parentCount, leafCount); countNodes(root->right, parentCount, leafCount); } int main() { printf("请输入二叉树的节点值,-1表示空节点:\n"); TreeNode* root = createTree(); int parentCount = 0, leafCount = 0; countNodes(root, &parentCount, &leafCount); printf("双亲节点个数为:%d\n", parentCount); printf("叶子节点个数为:%d\n", leafCount); return 0; } ``` 程序运行示例: ``` 请输入二叉树的节点值,-1表示空节点: 1 2 -1 -1 3 4 -1 -1 5 -1 -1 双亲节点个数为:4 叶子节点个数为:3 ``` 在示例中,我们输入的二叉树形如下图所示: ``` 1 / \ 2 3 / \ 4 5 ``` 因此,它的双亲节点个数为4,叶子节点个数为3。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值