Uva(Digit Generator,1583) 產生元

來源:互聯網
上載者:User

題目大概是這樣:

如果x加上x的各位元之和等於y,就說x是y的產生元.

給出n(1<=n<=100000),求n的最小產生元,  無解輸出0.

 例如 n=216,121,2005 應輸出 198 0 1979


當然,拿到題目我第一反應是枚舉,確實我使用枚舉AC了。。

並不是枚舉1-n. x=(n的位元)*9..  枚舉(n-x,n)即可

比如 216 只需要枚舉(n-3*9,n)..這是顯然的。

直接上代碼,儘管寫的很挫。

#include"cstdio"#include"cstdlib"#include"cstring"#include"algorithm"#include"iostream"using namespace std;int data[10];int main(){int n;int times;scanf("%d",×);for(int k=0;k<times;k++){scanf("%d",&n);int cnt=0;  //統計多少位 int tem=n;while(tem){cnt++;tem/=10;}int ok=0;for(int i=n-cnt*9;i<=n;i++){int sum=i;tem=i;while(tem){sum+=tem%10;tem/=10;}if(sum==n){ok=1;printf("%d\n",i);break; }}if(!ok)  printf("0\n");  //無解 }return 0;}


離線做法: 高效率

#include"cstdio"#include"cstring"const int maxn=100000+5;int ans[maxn];  void solve()  //離線做法 {    memset(ans,0,sizeof(ans));for(int i=1;i<maxn;i++){    int x=i,y=i;while(x){y+=x%10;x/=10;}if(ans[y]==0||i<ans[y])  ans[y]=i;} }int main(){int T,n;solve();    scanf("%d",&T);    while(T--)    {    scanf("%d",&n);    printf("%d\n",ans[n]);}}


如果不妥,還望指出。



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.