【发布时间】:2013-06-01 11:45:00
【问题描述】:
我正在尝试解决SPOJ problem "Ones and zeros":
某些正整数的十进制表示仅由 1 和 0 组成,并且至少有一位数字 1,例如101. 如果一个正整数不具有这样的性质,可以尝试将其与某个正整数相乘,以确定乘积是否具有这种性质。
我解决这个问题的方法只是做 BFS。获取仅包含 '1' 的字符串,然后对其进行 BFS,并在每一步添加 '1' 和 '0'。一直以字符串形式跟踪数字和余数。当余数为零时,该数被找到。
我的问题是:我的代码用于测试用例的时间太长,例如9999 或 99999。如何提高算法的运行时间?
// Shashank Jain
/*
BFS
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <climits>
#include <string>
#include <algorithm>
#include <vector>
#include <cmath>
#include <queue>
#include <stack>
#define LL long long int
using namespace std;
LL n;
string ans;
void bfs()
{
string str,first,second;
str+='1'; // number will start with '1' always
if(n==1)
{
ans=str;
return;
}
queue<pair<string,LL> >q; // pair of STRING(number) and long long int
// (to hold remainder till now)
pair<string,LL>p;
p=make_pair(str,1);
q.push(p);
LL rem,val,temp;
while(q.empty()==0)
{
p=q.front();
q.pop();
str=p.first;
val=p.second;
if(val==0) // remainder is zero means this is number
{
ans=str;
return ;
}
// adding 1 to present number
temp=val*10+1;
rem=(temp)%n;
firstone=str+'1';
p=make_pair(firstone,rem);
q.push(p);
// adding 0 to present number
temp=val*10+0;
rem=(temp)%n;
secondone=str+'0';
p=make_pair(secondone,rem);
q.push(p);
}
}
int main()
{
int t,i;
scanf("%d",&t);
while(t--)
{
scanf("%lld",&n);
bfs();
for(i=0;i<ans.size();i++)
{
printf("%c",ans[i]);
}
printf("\n");
}
return 0;
}
【问题讨论】:
-
@Christian Ammer - 感谢您的编辑!
-
不客气,将问题描述包含在问题中并以探测方式格式化代码总是一个好主意。
标签: c++ algorithm optimization