[PTA]7-39 龟兔赛跑 (20分)

乌龟与兔子进行赛跑,跑场是一个矩型跑道,跑道边可以随地进行休息。乌龟每分钟可以前进3米,兔子每分钟前进9米;兔子嫌乌龟跑得慢,觉得肯定能跑赢乌龟,于是,每跑10分钟回头看一下乌龟,若发现自己超过乌龟,就在路边休息,每次休息30分钟,否则继续跑10分钟;而乌龟非常努力,一直跑,不休息。假定乌龟与兔子在同一起点同一时刻开始起跑,请问T分钟后乌龟和兔子谁跑得快?

输入格式:
输入在一行中给出比赛时间T(分钟)。

输出格式:
在一行中输出比赛的结果:乌龟赢输出@@,兔子赢输出_,平局则输出--;后跟1空格,再输出胜利者跑完的距离。

输入样例:
242

输出样例:
@_@ 726

法一:
常规思路

#include <stdio.h>
int main(){
	int t,stop=0;
	int x=0,y=0;
	int k=0;
	scanf("%d",&t);
	if(t<=10){
		x=3*t;
		y=9*t;
	}else{
		x=30;
		y=90;
		stop=10;
		while(k==0){
			if(x<y){
			if(t-stop<=30){
				x=x+(t-stop)*3;
				k=1;
			}else{
				x=x+90;
				stop=stop+30;
			}
		}else{
			if(t-stop<=10){
				x=x+(t-stop)*3;
				y=y+(t-stop)*9;
				k=1;
			}else{
				x=x+30;
				y=y+90;
				stop=stop+10;
			}
		}
		}	
	}
	if(x>y){
		printf("@_@ %d",x);
	}else if(x==y){
		printf("-_- %d",y);
	}else{
		printf("^_^ %d",y);
	}
	return 0;
} 

法二:
主要思想是使用state来判断兔子休息与否,然后在每个state状态里设置一个子计时器,用来计算该状态经过的时间,再通过内嵌判断,来实现state的转换

#include<stdio.h>
int main(){
    int r_distance = 0,t_distance = 0,T,t=0,state =1,r_count=0,t_count=0;

    scanf("%d",&T);

    while(t<T){//总计时器从0开始,到T-1为止经过了T分钟
        t++;每分钟进行一次距离加和

        if(state == 1){//兔子跑
                r_count++;
                r_distance += 9;
                t_distance += 3;
                if(r_count == 10){

                    if(r_distance > t_distance){
                        state = 0;//rest for 30 minutes
                        t_count = 0;兔子休息,乌龟计时器初始化
                    }else{
                        state = 1;//run for another 10 minutes
                        r_count = 0;兔子继续跑,兔子计时器初始化
                    }//需要返回确认t是否溢出
                }else;

        }else{//兔子休息
            t_count++;
            t_distance += 3;
            if(t_count == 30){//兔子休息一轮了

                if(r_distance > t_distance){
                    state = 0;//rest for another 30 minutes
                    t_count = 0;兔子继续休息,乌龟计时器初始化
                }else{
                    state = 1;//run for 10 minutes
                    r_count = 0;//兔子开跑,兔子计时器初始化
                }//需要返回确认t是否溢出
            }else;
        }
    }
    if(r_distance > t_distance){
        printf("^_^ %d",r_distance);
    }else if(r_distance < t_distance){
        printf("@_@ %d",t_distance);
    }else{
        printf("-_- %d",t_distance);
    }

    return 0;
}

法二:
画出路程-时间图像就一目了然
作图
以90分钟为一个循环,每90分钟,兔子和乌龟跑过的路程相等

#include <stdio.h>

int main()
{
	int t;
	scanf("%d", &t);
	int t0 = t % 90;
	if (t0 > 30 && t0 < 45 || t0 > 60 && t0 < 90)
		printf("@_@ %d", t * 3); //乌龟赢
	else if (t0 > 0 && t0 < 30 || t0 > 45 && t0 < 60)
	{ //兔子赢
		int s;
		if (t0 > 0 && t0 < 10)
			s = 9 * t0;
		else if (t0 > 10 && t0 < 30)
			s = 90;
		else if (t0 > 45 && t0 < 50)
			s = 90 + 9 * (t0 - 40);
		else
			s = 180;
		printf("^_^ %d", t / 90 * 270 + s);
	}
	else
		printf("-_- %d", t * 3); //平局
	return 0;
}
发布了48 篇原创文章 · 获赞 0 · 访问量 303

猜你喜欢

转载自blog.csdn.net/weixin_46399138/article/details/105414218
今日推荐