航班时间
时间限制: 1S类别: 循环结构->较难
问题描述 :
【问题背景】
小h前往美国参加了蓝桥杯国际赛。小h的女朋友发现小h上午十点出发,上午十二点到达美国,于是感叹到“现在飞机飞得真快,两小时就能到美国了”。
小h对超音速飞行感到十分恐惧。仔细观察后发现飞机的起降时间都是当地时间。由于北京和美国东部有12小时时差,故飞机总共需要14小时的飞行时间。
不久后小h的女朋友去中东交换。小h并不知道中东与北京的时差。但是小h得到了女朋友来回航班的起降时间。小h想知道女朋友的航班飞行时间是多少。
【问题描述】
对于一个可能跨时区的航班,给定来回程的起降时间。假设飞机来回飞行时间相同,求飞机的飞行时间。
输入说明 :
从标准输入读入数据。
一个输入包含多组数据。
输入第一行为一个正整数T,表示输入数据组数。
每组数据包含两行,第一行为去程的 起降 时间,第二行为回程的 起降 时间。
起降时间的格式如下
h1:m1:s1 h2:m2:s2
或
h1:m1:s1 h3:m3:s3 (+1)
或
h1:m1:s1 h4:m4:s4 (+2)
表示该航班在当地时间h1时m1分s1秒起飞,
第一种格式表示在当地时间 当日 h2时m2分s2秒降落
第二种格式表示在当地时间 次日 h3时m3分s3秒降落。
第三种格式表示在当地时间 第三天 h4时m4分s4秒降落。
对于此题目中的所有以 h:m:s 形式给出的时间, 保证 ( 0<=h<=23, 0<=m,s<=59 ).
保证输入时间合法,飞行时间不超过24小时。
输出说明 :
输出到标准输出。
对于每一组数据输出一行一个时间hh:mm:ss,表示飞行时间为hh小时mm分ss秒。
注意,当时间为一位数时,要补齐前导零。如三小时四分五秒应写为03:04:05。
输入范例 :
3
17:48:19 21:57:24
11:05:18 15:14:23
17:21:07 00:31:46 (+1)
23:02:41 16:13:20 (+1)
10:19:19 20:41:24
22:19:04 16:41:09 (+1)
输出范例 :
04:09:05
12:10:39
14:22:05
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void sub(int a1, int b1, int c1, int &a2, int &b2, int &c2) {
int m1 = 0; int m2 = 0;
if (c2 < c1) {
c2 = c2 + 60 - c1;
m2 = 1;
}
else {
c2 -= c1;
}
if (b2 - m2 < b1) {
b2 = b2 - m2 + 60 - b1;
m1 = 1;
}
else {
b2 = b2 - m2 - b1;
}
a2 = a2 - m1 - a1;
}
void add(int a1, int b1, int c1, int& a2, int& b2, int& c2) {
c2 = (c2 + c1) / 2;
b2 = (b2 + b1) / 2;
a2 = (a2 + a1) / 2;
}
int main() {
int n;
cin >> n;
cin.ignore();//忽略cin输入后面的回车符号
for (int i = 0; i < n; i++) {
vector<int>a1, a2;
int b1=0, b2=0;//是否加一天
string s1, s2;
getline(cin,s1);
getline(cin, s2);
for (int i = 0; i < s1.length(); i++) {
if ((s1[i] >= '0' && s1[i] <= '9') && (s1[i + 1] >= '0' && s1[i + 1] <= '9')) {
a1.push_back(((int)s1[i] - 48) * 10 + ((int)s1[i + 1] - 48));
}
if (s1[i] == '+' && (s1[i + 1] >= '0' && s1[i + 1] <= '9')) {
b1 = (int)s1[i+1] - 48;
}
}
a1[3] += b1 * 24;
for (int i = 0; i < s2.length(); i++) {
if ((s2[i] >= '0' && s2[i] <= '9') && (s2[i + 1] >= '0' && s2[i + 1] <= '9')) {
a2.push_back(((int)s2[i] - 48) * 10 + ((int)s2[i + 1] - 48));
}
if (s2[i] == '+' && (s2[i + 1] >= '0' && s2[i + 1] <= '9')) {
b2 = (int)s2[i + 1] - 48;
}
}
a2[3] += b2 * 24;
sub(a1[0], a1[1], a1[2], a1[3], a1[4], a1[5]);
sub(a2[0], a2[1], a2[2], a2[3], a2[4], a2[5]);
add(a1[3], a1[4], a1[5], a2[3], a2[4], a2[5]);
cout.fill('0');
cout.width(2);
cout << a2[3];
cout << ":";
cout.fill('0');
cout.width(2);
cout << a2[4] ;
cout << ":";
cout.fill('0');
cout.width(2);
cout << a2[5]<<endl;
/*for (int i = 0; i < a1.size(); i++) {
cout << a1[i] << " ";
}
cout << endl;
for (int i = 0; i < a2.size(); i++) {
cout << a2[i] << " ";
}
cout << endl;*/
}
return 0;
}