您的位置:首页 > 其它

51nod 1109 01组成的N的倍数+

2016-12-02 18:33 323 查看
1109 01组成的N的倍数


基准时间限制:1 秒 空间限制:131072 KB 分值: 40 难度:4级算法题


 收藏


 关注

给定一个自然数N,找出一个M,使得M > 0且M是N的倍数,并且M的10进制表示只包含0或1。求最小的M。

例如:N = 4,M = 100。

Input
输入1个数N。(1 <= N <= 10^6)


Output
输出符合条件的最小的M。


Input示例
4


Output示例
100




首先 ,这个题大致就是一层一层的下去 具体就是 1为开头 下面一直接0 1  画成一个满二叉树的样子 

然后满二叉是肯定超时的  然后就用到了同余定理剪枝- -  秒过  

#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
queue<int>d;
queue<string> a;
int dp[1000000];//余数记录
int main()
{
int n;
while(cin>>n)
{
memset(dp,0,sizeof(dp));
int i=1,j=1;
d.push(1);
a.push("1");
int x;
while(1)
{
x=d.front()*10%n;
if(dp[x]==0)
{
dp[x]=1;
d.push(x);
a.push(a.front()+'0');
}
if(d.back()==0)
{
cout<<a.back()<<endl;
break;
}
x=(d.front()*10+1)%n;
if(dp[x]==0)
{
dp[x]=1;
d.push(x);
a.push(a.front()+'1');
}
if(d.back()==0)
{
cout<<a.back()<<endl;
break;
}
a.pop();
d.pop();
}
}
}


需要注意的一点就是用map 会超时   - - 大致就是关联容器比较慢吧

用字符数组记录也是可以的 而且用字符数组是比较快的

#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <queue>
#include <map>
using namespace std;
queue<int>d;
queue<string> a;
char dp[1000000];//字符数组记录
int main()
{
int n;

while(cin>>n)
{
memset(dp,'0',sizeof(dp));
int i=1,j=1;
d.push(1);
a.push("1");
int x;
while(1)
{
x=d.front()*10%n;
if(dp[x]=='0')
{
dp[x]='1';
d.push(x);
a.push(a.front()+'0');
}
if(d.back()==0)
{
cout<<a.back()<<endl;
break;
}
x=(d.front()*10+1)%n;
if(dp[x]=='0')
{
dp[x]='1';
d.push(x);
a.push(a.front()+'1');
}
if(d.back()==0)
{
cout<<a.back()<<endl;
break;
}
a.pop();
d.pop();
}
}
}

但是按照效率来说的话,还是手写的队列比较快,但是因为这个题的同余定理剪枝 ,所以空间有不确定性,大约的开下 ,反正比较看运气了

#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
const int mod=200000;
int d[200000];
string a[200000];
bool dp[1000000];
int main()
{
int n;
while(cin>>n)
{
memset(dp,true,sizeof(dp));
int i=0,j=1;
d[0]=1;
a[0]+='1';
int x;
while(1)
{
x=d[i]*10%n;
if(dp[x])
{
dp[x]=false;
d[j]=x;
a[j]=a[i]+'0';
if(d[j]==0)
{
cout<<a[j]<<endl;break;
} j=(j+1)%mod;
}

x=(d[i]*10+1)%n;
if(dp[x])
{
dp[x]=false;
d[j]=x;
a[j]=a[i]+'1';
if(d[j]==0)
{
cout<<a[j]<<endl;break;
}
j=(j+1)%mod;
}
i=(i+1)%mod;
}

// i=0;while(i<100000) {a[i].clear();i++;}
// memset(d,0,sizeof(d));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: