zoj 1871 || poj 2590 Steps(数学题 = =)

看这题,第一反应是,广搜嘛。

 

写了 = =MLE了。看了下范围2^31,我去啊。。我还开了俩队列,那绝对超了啊。 = =。。

 

后来想了想,数学方法,要么比前一个步子大,相等,或者小。就一直让它递增,以中间某个点对称,然后递减。

 

把这个序列算下,和到达点的差值,一定可以在序列里再找到一个步子,重复走下这个步子。

 

比如50

 

1 2 3 4 5 6 7 6 5 4 3 2 1 1 。

 

51

 

1 2 3 4 5 6 7 6 5 4 3 2 2 1。

 

56

 

1 2 3 4 5 6 7 7 6 5 4 3 2 1。

 

因为开始第一步和最后一步必须是1,所以这样想是对滴。

 

PS:POJ上的输入格式和ZOJ不一样,纠结。。

 

#include <stdio.h> #include <stdlib.h> #include <iostream> #include <string.h> using namespace std; int main(void) { int from,to; while( cin >> from >> to ) { if( from == to ) { cout << 0 << endl; continue; } int x = 0,steps = 0 ,i ; for( i=1; ;i++) { x += 2*i; if( x + from >= to ) break; } x -= 2*i; x += from; steps = i*2-2; if( x + i*2 == to ) { cout << steps+2 << endl; continue; } if( x + i <= to ) { steps++; int y = to - i - x; if( y!=0 ) steps++; cout << steps << endl; } else { int y = to - x; steps++; cout << steps << endl; } } return 0; }  

你可能感兴趣的:(zoj 1871 || poj 2590 Steps(数学题 = =))