PTA basic programming topics set - crawling worms

Original title link https://pintia.cn/problem-sets/14/problems/797

       Guilty when this problem began to consider a number of errors, starting with such considerations, according to the meaning of the title, every two minutes a worm crawling distance (UD) inch. Then the average creep distance per minute (U-D + 1) / 2 inch. Control sample data is then N = 12, U = 3, D = 1 is calculated climbed 8 minutes, of course, the result is wrong. Adjust the thinking, assuming that time is t, crawling distance s. When t = 0, s = 0; when t = 1, s = U; when t = 2, s = UD; when t = 3, s = UD + U; when t = 4, s = UD + UD; ....... therefore, can be drawn in the independent variable t s on a function F (t), which is a piecewise function, when the relation t% s and t when 2 == 0, f (t) = (t / 2) (UD); t% 2 == 1 when the time, f (t) = f (t-1) + U. There is a recursive form, because when the time t% 2 == 1, t-1 must be an even number, it may be further substituted for t-1 f (t) = (t / 2) (UD) when t is obtained odd f (t) = ((t-1) / 2) (UD) + U.

With the function, you can write code, the code is as follows:

. 1 #include <stdio.h>
 2  int main ( void ) {
 . 3      int T = 0 , s, n-, U, D;       // T represents time, s represents creeping distance 
. 4      Scanf ( " % D% D% D " , & n-, & U, & D);
 . 5      the while ( . 1 ) {
 . 6          IF (T% 2 == 0 ) {
 . 7              S = (T / 2 ) * (U - D);
 . 8          } the else {
 . 9              S = (( T - . 1 ) / 2) * (U - D) + U;
 10          }
 . 11          IF (S> = n-) {           // when creeping distance is greater than a specified distance out of the loop 
12 is              BREAK ;
 13 is          }
 14          T ++ ;
 15      }
 16      the printf ( " % D \ n- " , T);        // time it takes to print 
. 17      return  0 ;
 18 is }    

If the direct use of recursive form, as follows:

 1 #include <stdio.h>
 2 int distance(const int t, const int u, const int d);
 3 int main(void){
 4     int t, s, n, u, d;
 5     scanf("%d %d %d", &n, &u, &d);
 6     for(t = 0; ; t++){
 7         s = distance(t, u, d);
 8         if(s >= n){
 9             break;
10         }
. 11      }
 12 is      the printf ( " % D \ n- " , T);
 13 is      return  0 ;
 14  }
 15  
16  // calculate the indicated time points creeping distance 
. 17  int Distance ( const  int T, const  int U, const  int D) {
 18 is      IF (T% 2 == 0 ) {
 . 19          return (T / 2 ) * (U - D);
 20 is      } the else {
 21 is          return Distance (T -1, u, d) + u;
22     }
23 }

 

Guess you like

Origin www.cnblogs.com/zhang-15-506/p/12355143.html