码迷,mamicode.com
首页 > 其他好文 > 详细

K-Multiple Free set UVA-11246 (容斥原理)

时间:2020-02-04 21:59:31      阅读:64      评论:0      收藏:0      [点我收藏+]

标签:+=   com   space   过程   循环   type   mes   ring   log   

vjudge链接

原题链接

  • 题目大意

1~n 中找到一个最大的集合,使集合中不存在 a,b 两数,使 a*k==b。输出该集合中元素的数量。

  • 分析

只需输出元素的个数,故无需得到每个元素确切的值,只需模拟删除过程并统计数量即可。

容斥原理。首先删除所有 k 的倍数,元素个数变为 n/k ,显然 k^2 的倍数被多删除了一遍,故需要将 k^2 的倍数( n/k^2 个)重新加回,结果 k^3 的倍数又被多加回了一遍,又要减去 n/k^3 个…… 如此循环,直到没有多加和多减。

/*
 *lang C++ 5.3.0
 *user Weilin_C
 */

#include <iostream>
#include <sstream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cctype>

using namespace std;

int main()
{
    int num;
    int n, k;

    scanf("%d", &num);
    while (num--) {
        scanf("%d%d", &n, &k);
        int ans=n, pans=n/k, flag=-1;
        while (pans>0) {
            ans+=flag*pans;
            flag=-flag;
            pans/=k;
        }
        printf("%d\n", ans);
    }

    return 0;
}

by SDUST weilinfox
原文链接:https://www.cnblogs.com/weilinfox/p/12261580.html

K-Multiple Free set UVA-11246 (容斥原理)

标签:+=   com   space   过程   循环   type   mes   ring   log   

原文地址:https://www.cnblogs.com/weilinfox/p/12261580.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!