4
BFS: Memory Limit Exceed
Code:
#include <cstdio>#include <queue> using namespace std; int main(){ int n,m; queue<int> Q; while(scanf("%d%d",&n,&m)!=EOF){ if(n==0&&m==0) break; while(Q.empty()==false){ Q.pop(); } Q.push(n); int ans=0; while(Q.empty()==false){ int now=Q.front(); Q.pop(); ++ans; if(now*2<=m) Q.push(now*2); if(now*2+1<=m) Q.push(now*2+1); } printf("%d\n",ans); } return 0;} /************************************************************** Problem: 1113 User: lcyvino Language: C++ Result: Memory Limit Exceed****************************************************************/
改用遞迴: Time Limit Exceed
Code:
#include <cstdio> using namespace std; long long countNode(long long x,long long m){ if(x>m) return 0; else{ x=x<<1; return 1+countNode(x,m)+countNode(x+1,m); }} int main(){ long long n,m; while(scanf("%lld%lld",&n,&m)!=EOF){ if(n==0&&m==0) break; printf("%lld\n",countNode(n,m)); } return 0;} /************************************************************** Problem: 1113 User: lcyvino Language: C++ Result: Time Limit Exceed****************************************************************/
只好用公式:
Code:
#include <cstdio>#include <math.h> using namespace std; int main(){ int n,m; while(scanf("%d%d",&n,&m)!=EOF){ if(n==0&&m==0) break; int depth_n=(int)(log2(n)+1); int depth_m=(int)(log2(m)+1); int sum=0; int num=1; for(int index=0;index<depth_m-depth_n;++index){ sum+=num; num*=2; } long long leftNode=n,rightNode=n; for(int index=0;index<depth_m-depth_n;++index){ leftNode=2*leftNode; rightNode=2*rightNode+1; } if(m>=rightNode){ sum+=rightNode-leftNode+1; }else{ if(m>=leftNode) sum+=m-leftNode+1; } printf("%d\n",sum); } return 0;} /************************************************************** Problem: 1113 User: lcyvino Language: C++ Result: Accepted Time:0 ms Memory:1032 kb****************************************************************/