ZJU1105-FatMouse‘s Tour

题目链接:ZJU1105-FatMouse’s Tour
在此转到关于本书博客ACM大学生程序设计竞赛在线题库最新精选题解(赵端阳)部分解析
学到了sscanf()从字符中读入数据操作。不过说到底还是题目较怪,数字输入一般以-1或0等等数结尾,这样容易处理,毕竟考算法能力而不是考察奇怪的解决输入流能力,但本题以’‘java’'作为结尾标志就很离谱。
思路并不难,主要是对字符串处理,给出两种代码:
c++代码,g++ 6.5.0编译。用c++中string类可以安全使用getline();
ac代码

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<string>
#include<math.h>
int main() {
    
    
	int x0, y0, x1, x2, y1, y2, time;
	double dist,d;
	string str;
	char *p;

	while (cin >> x0 >> y0) {
    
    		//x0,y0 is useless, but still need to be read in
		cin.get();//读换行符
		dist = 0.0;
		while (getline(cin, str) && str != "java") {
    
    
			p = &str[0];		//相当于把string类变成char型,p指向开头
			sscanf(p, "%d%d%d%d", &x1, &y1, &x2, &y2);
			d = (x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2);
			dist += sqrt(d);
		}
		dist = dist * 2 / 1000.0 / 20.0*60.0;
		time = int(dist + 0.5);		//convert double to int
		cout << time / 60 << ':';
		if (time % 60 < 10)cout << '0' << time % 60 << endl;//不够两位补零
		else cout << time % 60 << endl;
		//当然也可以写成
		//printf("%d:%02%d\n",time/60,time%60);
	}
	return 0;
}

只有c才能运行gets()等函数,因为此函数从缓存读,越界会不安全。在gcc 6.5.0下支持。
另外书中%dist应为印刷错误,应该是%d
ac代码:

#include<stdio.h>
#include<math.h>
double distance(double x1,double y1,double x2,double y2)
{
    
    
return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}
int main()
{
    
    
double x0,y0;
double x1,x2,y1,y2;
char street[80];
while(scanf("%lf%lf\n",&x0,&y0)!=EOF)//注意换行符
{
    
    
double dist=0;
gets(street);
while(street[0]!='j')
{
    
    
sscanf(street,"%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
dist+=distance(x1,y1,x2,y2);
gets(street);
}
dist=60*2.0*dist/20000.0;
int spend=floor(dist+0.5);
printf("%d:%02d\n",spend/60,spend%60);
}
return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43305312/article/details/109025662