1. 程式人生 > >第六屆藍橋杯C++B組——移動距離(曼哈頓距離)

第六屆藍橋杯C++B組——移動距離(曼哈頓距離)

X星球居民小區的樓房全是一樣的,並且按矩陣樣式排列。其樓房的編號為1,2,3…
當排滿一行時,從下一行相鄰的樓往反方向排號。
比如:當小區排號寬度為6時,開始情形如下:

1 2 3 4 5 6
12 11 10 9 8 7
13 14 15 …..

我們的問題是:已知了兩個樓號m和n,需要求出它們之間的最短移動距離(不能斜線方向移動)

輸入為3個整數w m n,空格分開,都在1到10000範圍內
w為排號寬度,m,n為待計算的樓號。
要求輸出一個整數,表示m n 兩樓間最短移動距離。

例如:
使用者輸入:
6 8 2
則,程式應該輸出:
4

再例如:
使用者輸入:
4 7 20
則,程式應該輸出:
5

資源約定:
峰值記憶體消耗 < 256M
CPU消耗 < 1000ms

因為只能上下移動,所以最短距離就是曼哈頓距離
我用的是最原始樸素的方法,每個點的座標一個個算,也懶得去找什麼規律簡化,我們沒文化的人寫程式碼從來都是這樣的!
當然能不能過所有資料,我也不知道

#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <cstdio>
#include <set>
#include <math.h> #include <algorithm> #include <queue> #define INF 0x3f3f3f3f #define MAXN 100005 #define Mod 1000000007 using namespace std; int main() { int w,m,n; scanf("%d%d%d",&w,&m,&n); int x1=1,y1=1,cnt=1; while(cnt<m) { cnt++; if(y1%2
) { x1++; if(x1>w) { x1=w; y1++; } } else { x1--; if(x1<1) { x1=1; y1++; } } } //cout<<x1<<" "<<y1<<endl; int x2=1,y2=1; cnt=1; while(cnt<n) { cnt++; if(y2%2) { x2++; if(x2>w) { x2=w; y2++; } } else { x2--; if(x2<1) { x2=1; y2++; } } } //cout<<x2<<" "<<y2<<endl; int ans=abs(x1-x2)+abs(y1-y2); cout<<ans; return 0; }