POJ-2773 Happy 2006(容斥,二分,dfs)

Happy 2006

Two positive integers are said to be relatively prime to each other if the Great Common Divisor (GCD) is 1. For instance, 1, 3, 5, 7, 9…are all relatively prime to 2006.

Now your job is easy: for the given integer m, find the K-th element which is relatively prime to m when these elements are sorted in ascending order.
Input
The input contains multiple test cases. For each test case, it contains two integers m (1 <= m <= 1000000), K (1 <= K <= 100000000).
Output
Output the K-th element in a single line.
Sample Input
2006 1
2006 2
2006 3
Sample Output
1
3
5

題意:給你m和k,從小到大排序,問第k個與m互質的數是多少。

思路:首先打一個素數表,把m分解成素因數,然後我們可以通過容斥定理求出x以內與m互質的數的個數,然後我們通過二分來找x,使得find(x)=k,滿足條件的x會有多個,最後循環遞減找一下最小的滿足條件的x就是答案。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <queue>
#include <map>
#include <algorithm>
#include <set>
#include <functional>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
const int INF = 1e9 + 5;
const int MAXN = 1000007;
const int MOD = 30021;
const double eps = 1e-8;
const double PI = acos(-1.0);

int prime[MAXN], primesize;
bool isprime[MAXN];
void getlist(int listsize)
{
    memset(isprime, 1, sizeof(isprime));
    isprime[1] = false;
    for (int i = 2; i <= listsize; i++)
    {
        if (isprime[i])prime[++primesize] = i;
        for (int j = 1; j <= primesize&&i*prime[j] <= listsize; j++)
        {
            isprime[i*prime[j]] = false;
            if (i%prime[j] == 0)break;
        }
    }
}

int t;
int num[10];

void solve(int x)
{
    t = 0;
    memset(num, 0, sizeof num);
    for (int i = 1; prime[i]*prime[i] <= x; i++)
    {
        if (x%prime[i] == 0)
            t++;
        while (x%prime[i]==0)
        {
            num[t] = prime[i];
            x /= prime[i];
        }
    }
    if (x != 1)
        num[++t] = x;
}

LL ans;

void dfs(LL k,LL place,LL mul,LL flag)
{
    if (place == t)
    {
        if (mul != 1)
            if (flag)ans += k / mul;
            else ans -= k / mul;
        return;
    }
    dfs(k, place + 1, mul, flag);
    dfs(k, place + 1, mul*num[place + 1], flag ^ 1);
}

LL find(LL x)
{
    ans = 0;
    dfs(x, 0, 1, 0);
    return x - ans;
}

LL Find(int x)
{
    LL mid;
    LL l = 1;
    LL r = 1LL << 60;
    while (l<r)
    {
        mid = (l + r) / 2;
        if (find(mid) == x)
            return mid;
        if (find(mid) > x)
            r = mid;
        else
            l = mid;
    }
}

int main()
{
    int m, K;
    LL s;
    getlist(1000003);
    while (scanf("%d%d",&m,&K)!=EOF)
    {
        solve(m);
        s=Find(K);
        while (find(s-1)==K)
            s--;
        printf("%lld\n", s);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章