標題:螺旋折線
如圖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
不能通過工程設置而省略常用頭文件。
提交程序時,注意選擇所期望的語言類型和編譯器類型。
思路:模擬螺旋折線 從0,0開始 左上右下
代碼:
#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
int X,Y;
//模擬螺旋折線 從0,0開始 左上右下
int main(){
int arr[200][200];
memset(arr,0,sizeof(arr));
arr[0][0] = 0;
cin>>X>>Y;
int t = max(abs(X),abs(Y));
int i = 0,j = 0;
int ans = 0;
for(int x=0,y=0;x<=t,y<=t;x++,y++){
//左走一次到底
while(i>-x-1){
i--;
ans +=1;
arr[i][j] = ans;
if(i == X && j == Y){
cout<<ans<<endl;
return 0;
}
}
//上走到底
while(j<y+1){
j++;
ans +=1;
arr[i][j] = ans;
if(i == X && j == Y){
cout<<ans<<endl;
return 0;
}
}
//右
while(i<x+1){
i++;
ans+=1;
arr[i][j] = ans;
if(i == X && j == Y){
cout<<ans<<endl;
return 0;
}
}
//下
while(j>-y-1){
j--;
ans+=1;
arr[i][j] = ans;
if(i == X && j == Y){
cout<<ans<<endl;
return 0;
}
}
}
return 0;
}