【poj2773】 Happy 2006

來源:互聯網
上載者:User

標籤:

http://poj.org/problem?id=2773 (題目連結)

題意:給出兩個數m,k,要求求出從1開始與m互質的第k個數。

Solution

  資料範圍很大,直接類比顯然是不行的,我們需要用到一些奇奇怪怪的方法。

  考慮是否可以通過某些途徑快速得到解,然而並沒有頭緒。正難則反,能不能通過計算不與m互質的數的個數來得到互質的數的個數呢?答案是可行的,我們可以運用容斥。

  二分一個答案mid,容斥統計出在區間[1,mid]中是m的質因子的倍數的數的個數ans,然後我們可以用mid-ans得到區間中有多少個與m互質的數,不斷二分下去,直到得出答案。 

  容斥統計的經典應用。

代碼:

// poj2773#include<algorithm>#include<iostream>#include<cstdlib>#include<cstring>#include<cstdio>#include<cmath>#define LL long long#define inf (1ll<<62);#define Pi acos(-1.0)#define free(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout);using namespace std;int n,cnt,p[500],a[200],vis[2010];LL ans,m,k,mid;LL gcd(LL a,LL b) {    return a%b==0 ? b : gcd(b,a%b);}void dfs(int x,int y,int z) {    if (x==n+1) {        if (y>0) {            if (y&1) ans+=mid/z;            else ans-=mid/z;        }        return;    }    dfs(x+1,y,z);    LL tmp=a[x]/gcd(z,a[x]);    if ((double)tmp*z<=mid) dfs(x+1,y+1,z*tmp);}int main() {    for (int i=2;i<=2000;i++) if (!vis[i]) {            for (int j=i+i;j<=2000;j+=i) vis[j]=1;            p[++cnt]=i;        }    while (scanf("%lld%lld",&m,&k)!=EOF) {        memset(a,0,sizeof(a));n=0;        for (int i=1;i<=cnt;i++)            if (m%p[i]==0) {                while (m%p[i]==0 && m>1) m/=p[i];                a[++n]=p[i];            }        if (m>1) a[++n]=m;        sort(a+1,a+1+n);        LL L=1,R=inf;        while (L<R) {            mid=(L+R)>>1;            ans=0;dfs(1,0,1);            if (mid-ans>=k) R=mid;            else L=mid+1;        }        printf("%lld\n",L);    }    return 0;}

  

【poj2773】 Happy 2006

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.