SPOJの問題「1と0」を解決しようとしています:
特定の正の整数は、1 と 0 のみで構成される 10 進数表現を持ち、少なくとも 1 桁の 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;
}