标题:螺旋折线
如图p1.png所示的螺旋折线经过平面上所有整点恰好一次。
对于整点(X, Y),我们定义它到原点的距离dis(X, Y)是从原点到(X, Y)的螺旋折线段的长度。
例如dis(0, 1)=3, dis(-2, -1)=9
给出整点坐标(X, Y),你能计算出dis(X, Y)吗?
【输入格式】
X和Y
对于40%的数据,-1000 <= X, Y <= 1000
对于70%的数据,-100000 <= X, Y <= 100000
对于100%的数据, -1000000000 <= X, Y <= 1000000000
【输出格式】
输出dis(X, Y)
【样例输入】
0 1
【样例输出】
3
资源约定:
峰值内存消耗(含虚拟机) < 256M
CPU消耗 < 1000ms
请严格按要求输出,不要画蛇添足地打印类似:“请您输入...” 的多余内容。
注意:
main函数需要返回0;
只使用ANSI C/ANSI C++ 标准;
不要调用依赖于编译环境或操作系统的特殊函数。
所有依赖的函数必须明确地在源文件中 #include <xxx>
不能通过工程设置而省略常用头文件。
提交程序时,注意选择所期望的语言类型和编译器类型。
方法1和方法2的性能分析:
| (X,Y) | V1输出,timeCost/s | V2输出,timeCost/s |
| 555,555 | 1232100,0.006 | 1232100,0 |
| 888,888 | 3154176,0.018 | 3154176,0 |
| 1000,1000 | 4000000,0.02 | 4000000,0 |
| 6666,6666 | 177742224,0.738 | 177742224,0.002 |
| 9999,9999 | 399920004,1.77 | 399920004,0 |
| 10100,10100 | 408040000,1.876 | 408040000,0 |
| 99999,99999 | 超时 | 39999200004,0.003 |
| 99999999 99999999 | 超时 | 39999999200000004,2.54 |
| 1000000000 1000000000 | 超时 | 4000000000000000000,26.343 |
结论:经过我的反复思考与打磨后,方法2对付70%的测试用例还是够用的。
未完待续。。。
最初的代码 V1codes:
#include <iostream>
#include <time.h>using namespace std;clock_t start,stop;
double duration;typedef long long LL;//解题思路:单循环,走螺旋线走到终点
LL X,Y;
LL curX,curY;
LL paces;
LL width;
LL hasWalked;//当前直线段已经走的单位长度
char curDir;//当前前进方向:分为:上U,下D,左L,右Rvoid drawOnce(){paces++;hasWalked++;switch(curDir){case 'U':{curY++;if(hasWalked==width){width++;curDir='R';hasWalked=0;}break;}case 'D':{curY--;if(hasWalked==width){curDir='L';width++;hasWalked=0;}break;}case 'L':{curX--;if(hasWalked==width){curDir='U';hasWalked=0;}break;}case 'R':{curX++;if(hasWalked==width){curDir='D';hasWalked=0;}break;}}
}void loopTillEnd(){paces=0;width=1;curDir='L';hasWalked=0;while(true){drawOnce();if(curX==X && curY==Y)break;}cout<<paces<<endl;
}int main()
{cin>>X>>Y;start=clock();loopTillEnd();stop=clock();duration=((double)(stop-start))/CLK_TCK;cout<<"Time cost="<<duration<<endl;return 0;
}
打磨后的高性能代码:
V2codes with better performace:
#include <iostream>
#include <cmath>
#include <time.h>using namespace std;clock_t start,stop;
double duration;typedef long long LL;LL X,Y;
LL curX,curY;
LL postX,postY;
LL paces;
LL width;char curDir;//当前前进方向:分为:上U,下D,左L,右Rvoid drawOnce(){//新思路:每次走width步,过程中判断(X,Y)是否在(postX,postY)和(curX,curY)之间//若在,则向前回溯postX=curX;postY=curY;paces+=width;switch(curDir){case 'U':{curY+=width;width++;curDir='R';break;}case 'D':{curY-=width;curDir='L';width++;break;}case 'L':{curX-=width;curDir='U';break;}case 'R':{curX+=width;curDir='D';break;}}
}LL check(){LL backPace=-1;if( Y==curY && Y==postY && (X-curX)*(X-postX)<=0 )//若为y=AbackPace=abs(curX-X);else if( X==curX && X==postX && (Y-postY)*(Y-curY)<=0 )//若为X=AbackPace=abs(curY-Y);return backPace;
}void loopTillEnd(){paces=0;width=1;curDir='L';while(true){drawOnce();if( check()>=0 ){cout<<paces-check()<<endl;break;}}}int main()
{cin>>X>>Y;// start=clock();loopTillEnd();// stop=clock();// duration=((double)(stop-start))/CLK_TCK;// cout<<"Time cost="<<duration<<endl;return 0;
}