首页 > 试题广场 >

2018校招面试题——羽毛球馆

[问答题]

2018校招面试题——羽毛球馆


[TOC]

说明

  • 本作业限时2天完成
  • 可以选用擅长的语言完成,例如C、C++、Java、C#、Javascript、Python、Scala等
  • 可以使用第三方库简化代码(如日期,时间、集合操作等)
  • 作业的输入和输出必须和题目的测试用例输出严格一致
  • 作业完成后必须附上 Readme 纯文本文档(推荐使用 markdown 排版)
  • Readme文档中应描述如何运行单元测试或主程序来证明作业的正确性(至少针对测试用例输入能够得到对应输出)

家庭作业部分

小明是一个羽毛球场馆的管理员,管理着四个羽毛球场地(A,B,C,D场地),负责场地的维护和预订工作。为了简化自己的工作,场地只接受整点预订,预订以小时为单位。

羽毛球场的收费标准如下:

  • 周一到周五:
    • 9:00 ~ 12:00 30元/时
    • 12:00 ~ 18:00 50元/时
    • 18:00 ~ 20:00 80元/时
    • 20:00 ~ 22:00 60元/时
  • 周六及周日
    • 9:00 ~ 12:00 40元/时
    • 12:00 ~ 18:00 50元/时
    • 18:00 ~ 22:00 60元/时

羽毛球场馆在预订之后,可以接受取消预订,不过取消预订需要交违约金,违约金的计算规则如下:

  • 周一到周五的预订取消收取全部费用的50%作为违约金
  • 周六周日的预订取消收取全部费用的25%作为违约金
由于手头还有其他工作,小明希望能够借助计算机程序来自动化处理预订及取消预订的事务,并且希望程序能够打印出场馆的收入汇总情况。

程序输入

预订:用户预订以字符串的形式输入,一行字符串代表一个预定

  • 格式为{用户ID} {预订日期 yyyy-MM-dd} {预订时间段 HH:mm~HH:mm} {场地},如U123 2016-06-02 20:00~22:00 A,代表用户U123预定2016年06月02日晚上20:00到22:00的场地A的时间段
  • 时间段的起止时间必然为整小时,否则报错
  • 如预订与已有预订冲突,也会报错

取消预定:用户取消预定,输入也以一行字符串的形式表现

  • 格式为{用户ID} {预订日期 yyyy-MM-dd} {预订时间段 HH:mm~HH:mm} {场地} {取消标记},如U123 2016-06-02 20:00~22:00 A C,代表用户U123取消其在2016年06月02日晚上20:00到22:00在场地A的预订,其中取消标记C代表Cancel
  • 取消标记只能是C,若为其他字符则报错
  • 时间段的起止时间必然为整小时,否则报错
  • 只能完整取消之前的预订,不能取消部分时间段
  • 取消预订的请求,必须与之前的预订请求严格匹配,需要匹配的项有用户ID,预订日期,预订时间段,场地

打印场馆收入汇总: 将所有的预订和取消预订带来的收入汇总信息打印出来

  • 格式为,输入一个空行,代表打印收入汇总

程序输出

收入汇总:以文本的形式输出当前系统所有预订以及取消预订所带来的收入情况,以不同的场地分组,一个可能的输出如下所示:

收入汇总
---
场地:A
2016-06-02 09:00~10:00 违约金 15元
2016-06-02 10:00~12:00 60元
2016-06-03 20:00~22:00 120元
小计:195元

场地:B
2016-06-04 09:00~10:00 40元
小计:40元

场地:C
小计:0元

场地:D
小计:0元
---
总计: 235元

注意:

  • 如果同一场地同一时间段有多条预定记录,则显示多条
  • 收入记录以时间顺序升序排列


测试用例1

注意:>开头表示命令行输出,以下测试用例都遵循此例

abcdefghijklmnopqrst1234567890
> Error: the booking is invalid!
U001 2016-06-02 22:00~22:00 A
> Error: the booking is invalid!
U002 2017-08-01 19:00~22:00 A
> Success: the booking is accepted!
U003 2017-08-02 13:00~17:00 B
> Success: the booking is accepted!
U004 2017-08-03 15:00~16:00 C
> Success: the booking is accepted!
U005 2017-08-05 09:00~11:00 D
> Success: the booking is accepted!

> 收入汇总
> ---
> 场地:A
> 2017-08-01 19:00~22:00 200元
> 小计:200元
>
> 场地:B
> 2017-08-02 13:00~17:00 200元
> 小计:200元
>
> 场地:C
> 2017-08-03 15:00~16:00 50元
> 小计:50元
>
> 场地:D
> 2017-08-05 09:00~11:00 80元
> 小计:80元
> ---
> 总计:530元

测试用例2

U002 2017-08-01 19:00~22:00 A
> Success: the booking is accepted!
U003 2017-08-01 18:00~20:00 A
> Error: the booking conflicts with existing bookings!
U002 2017-08-01 19:00~22:00 A C
> Success: the booking is accepted!
U002 2017-08-01 19:00~22:00 A C
> Error: the booking being cancelled does not exist!
U003 2017-08-01 18:00~20:00 A
> Success: the booking is accepted!
U003 2017-08-02 13:00~17:00 B
> Success: the booking is accepted!

> 收入汇总
> ---
> 场地:A
> 2017-08-01 18:00~20:00 160元
> 2017-08-01 19:00~22:00 违约金 100元
> 小计:260元
>
> 场地:B
> 2017-08-02 13:00~17:00 200元
> 小计:200元
>
> 场地:C
> 小计:0元
>
> 场地:D
> 小计:0元
> ---
> 总计:460元


办公室面试部分

现在,羽毛球场推出不定期的优惠活动。活动期间,价格在总价上打相应折扣(折扣四舍五入到元)。管理员小明希望能够动态更新优惠信息,以更优惠的价格来服务到场馆运动的羽毛球爱好者。

球场的优惠活动存放在程序的某文本资源文件中,其中的每一行字符串代表一个优惠时间段,每个优惠时段的格式为,{起始日期:yyyy-MM-dd} {终止日期(包含):yyyy-MM-dd} {折扣:1-9代表相应的折扣},以下为范例:

2016-04-01 2016-04-02 6
2017-08-01 2017-08-03 8

请修改程序实现优惠后的收入汇总,需要注意之前的所有需求保持不变。



测试用例


注意:以下结果基于上述范例优惠信息计算得出

abcdefghijklmnopqrst1234567890
> Error: the booking is invalid!
U001 2016-06-02 22:00~22:00 A
> Error: the booking is invalid!
U002 2017-08-01 19:00~22:00 A
> Success: the booking is accepted!
U003 2017-08-02 13:00~17:00 B
> Success: the booking is accepted!
U004 2017-08-03 15:00~16:00 C
> Success: the booking is accepted!
U005 2017-08-05 09:00~11:00 D
> Success: the booking is accepted!

> 收入汇总
> ---
> 场地:A
> 2017-08-01 19:00~22:00 160元 已优惠:40元
> 小计:160元
>
> 场地:B
> 2017-08-02 13:00~17:00 160元 已优惠:40元
> 小计:160元
>
> 场地:C
> 2017-08-03 15:00~16:00 40元 已优惠:10元
> 小计:40元
>
> 场地:D
> 2017-08-05 09:00~11:00 80元
> 小计:80元
> ---
> 总计:440元

public class Customer {
String userID;
int year;
int month;
int day;
int startClock;
int endClock;
String place;

public Customer(String id, int year, int month, int day, int startClock, int endClock, String placa) {
this.userID = id;
this.year = year;
this.month = month;
this.day = day;
this.startClock = startClock;
this.endClock = endClock;
this.place = placa;
}

public boolean isIDEuqal(Customer c) {
if (this.userID.equals(c.userID))
return true;
return false;
}

public boolean isDateEqual(Customer c) {
if (this.year == c.year && this.month == c.month && this.day == c.day)
return true;
return false;
}

public boolean isPlaceEqual(Customer c) {
if (this.place.equals(c.place))
return true;
return false;
}

public boolean isEqual(Customer c) {
if (this.userID.equals(c.userID) && this.year == c.year && this.month == c.month && this.day == c.day && this.startClock == c.startClock && this.endClock == c.endClock)
return true;
return false;
}


public boolean isTimeConflict(Customer c) {
if (isDateEqual(c) && 
((this.startClock < c.startClock && this.endClock < c.endClock && this.endClock > c.startClock) 
||(this.startClock > c.startClock && this.startClock < c.endClock && this.endClock > c.startClock && this.endClock < c.endClock)
||(this.startClock > c.startClock && this.startClock < c.endClock && this.endClock > c.endClock)
||(c.startClock < this.startClock && c.endClock < this.endClock && c.endClock > this.startClock)
||(c.startClock > this.startClock && c.startClock < this.endClock && c.endClock > this.startClock && c.endClock < this.endClock)
||(c.startClock > this.startClock && c.startClock < this.endClock && c.endClock > this.endClock))
&& isPlaceEqual(c))
return true;
return false;
}

}



import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
static String[] str = new String[21];
/*
str[1]: user ID
str[4]: start year
str[6]: start month
str[8]: start day
str[10]: start clock
str[14]: end clock
str[18]: Accept
str[20]: Concel
*/
static int minStartClock = 9;
static int maxEndClock = 22;
static List<Customer>   bookList = new LinkedList<>();
static List<Customer> concelList = new ArrayList<>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\n");
String line = "";
while(line.length() != 1 && line != " ") {
line = sc.nextLine();
// System.out.println(line);
if(line.length() != 1 && line != " ")
mainProcess(line);
}
printResult();
// String [] line = new String[6];
// line[0] = "U002 2017-08-01 19:00~22:00 A";
// line[1] = "U003 2017-08-01 18:00~20:00 A";
// line[2] = "U002 2017-08-01 19:00~22:00 A C";
// line[3] = "U002 2017-08-01 19:00~22:00 A C";
// line[4] = "U003 2017-08-01 18:00~20:00 A";
// line[5] = "U003 2017-08-02 13:00~17:00 B";
// for (String l:line) {
// mainProcess(l);;
// }
// printResult();
}
public static void mainProcess(String line) {
String userID;
int year;
int month;
int day;
int startClock;
int endClock;
String place;

String bookPattern = "(U)(\\d{3})(\\s)(\\d{4})(-)(\\d{2})(-)(\\d{2})(\\s)(\\d{2})(:)(00)(~)(\\d{2})(:)(00)(\\s)([A-D])";
String concelPattern = "(U)(\\d{3})(\\s)(\\d{4})(-)(\\d{2})(-)(\\d{2})(\\s)(\\d{2})(:)(00)(~)(\\d{2})(:)(00)(\\s)([A-D])(\\s)([C])";
boolean isBook = Pattern.matches(bookPattern, line);
boolean isConcel = Pattern.matches(concelPattern, line);
// System.out.println(line);
if (isBook) {
// System.out.println(Pattern.matches(bookPattern, line));
Pattern p = Pattern.compile(bookPattern);
Matcher m = p.matcher(line);
// System.out.println(m.groupCount());
m.find();
for (int j = 0; j < m.groupCount()+1; j++) {
str[j] = m.group(j);
// System.out.println(str[j]);
}
// System.out.println(str[20]);
userID = str[2];
year = Integer.valueOf(str[4]);
month = Integer.valueOf(str[6]);
day = Integer.valueOf(str[8]);
startClock = Integer.valueOf(str[10]);
endClock = Integer.valueOf(str[14]);
place = str[18];
// bookMessage = year + month + day + 
// 如果与预定表达式一样的话,那么看预定的时间是否相等,预定的开始时间是否小于最小开始时间,结束时间是否大于最大结束时间,如果是的话,打印预定不正确错误。
if (Integer.valueOf(startClock) == Integer.valueOf(endClock) 
|| Integer.valueOf(startClock) < minStartClock 
|| Integer.valueOf(endClock) > maxEndClock)
printInvalidBookError();
else {
Customer cus = new Customer(userID, year, month, day, startClock, endClock, place);
book(cus);
}
} else if (isConcel) {
Pattern p = Pattern.compile(concelPattern);
Matcher m = p.matcher(line);
// System.out.println(m.groupCount());
m.find();
for (int j = 0; j < m.groupCount()+1; j++) {
str[j] = m.group(j);
// System.out.println(str[j]);
}
// System.out.println(str[20]);
userID = str[2];
year = Integer.valueOf(str[4]);
month = Integer.valueOf(str[6]);
day = Integer.valueOf(str[8]);
startClock = Integer.valueOf(str[10]);
endClock = Integer.valueOf(str[14]);
place = str[18];
Customer cus = new Customer(userID, year, month, day, startClock, endClock, place);
concelBook(cus); 

else {
printInvalidBookError();

}

public static void book(Customer cus){
for (Customer c:bookList) {
if (c.isTimeConflict(cus)) {
printConflictError();
return;
}
}
bookList.add(cus);
printBookSuccess();
}
public static void concelBook(Customer cus){
boolean rem = false;
for (Customer c:bookList) {
if (cus.isEqual(c)) {
bookList.remove(c);
concelList.add(cus);
printBookSuccess();
rem = true;
}
}
if (!rem)
printConcelError();
}

public static void printResult() {
String [] placeIncome = new String[4];
int [] placePrice = new int[4];
int  bookIncome;
int concelIncome;
for (int j = 'A', k = 0; j <= 'D'; j ++, k++) {
placeIncome[k] = "场地" + String.valueOf((char)(j)) + ":\n";
}
System.out.println("\n" + "收入汇总\n" + "---");
for (Customer c:bookList) {
bookIncome = calPrice(c);
for (int j = 'A', k = 0; j <= 'D'; j ++, k++) {
if ((String.valueOf((char)(j))).equals(c.place)) {
placePrice[k] += bookIncome;
placeIncome[k] += (c.year + "-" + (c.month < 10 ? ("0" + c.month):c.month) + "-" + (c.day < 10 ? ("0" + c.day):c.day) + " "
+ (c.startClock < 10 ? ("0" + c.startClock):c.startClock)+":"+"00"+"~"
+(c.endClock< 10 ? ("0" + c.endClock):c.endClock)+":"+"00"
+ " " + bookIncome + "元" + "\n");
}
}
// System.out.println(bookIncome);
}
for (Customer c:concelList) {
concelIncome = calConcel(c); 
for (int j = 'A', k = 0; j <= 'D'; j ++, k++) {
if ((String.valueOf((char)(j))).equals(c.place)) {
placePrice[k] += concelIncome;
placeIncome[k] += (c.year + "-" + (c.month < 10 ? ("0" + c.month):c.month) + "-" + (c.day < 10 ? ("0" + c.day):c.day) + " "
+ (c.startClock < 10 ? ("0" + c.startClock):c.startClock)+":"+"00"+"~"
+(c.endClock< 10 ? ("0" + c.endClock):c.endClock)+":"+"00"
+ " 违约金" + " " + concelIncome + "元\n");
}
}
}
int i = 0;
int sumPrice = 0;
for(String p:placeIncome) {
sumPrice += placePrice[i];
System.out.print(p);
System.out.println("小计:" + placePrice[i++] + "元");
System.out.println();
}
System.out.println("---\n" + "总计:" + sumPrice + "元");
}
public static int calConcel(Customer c) {
return (int) (calPrice(c) * (getWeek(c) <= 5 ? 0.5:0.25));
}
public static int getWeek(Customer c) {
String[] weeks = {"星期一","星期二","星期三","星期四","星期五","星期六", "星期日"}; 
String strDate = c.year + "-" + c.month + "-" + c.day;
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try { 
date = f.parse(strDate);// 将字符串转换为日期 
} catch (ParseException e) { 
System.out.println("输入的日期格式不合理!"); 
}
SimpleDateFormat sdf = new SimpleDateFormat("EEEE"); 
String week = sdf.format(date); 
for(int i = 0; i < weeks.length; i++) {
if (week.equals(weeks[i]))
return ++i;
}
return 0;
}
public static int calPrice(Customer c) {
int [] workDayPrice = {30, 50 ,80, 60};
int [] weekDayPrice = {40 , 50, 60};
int week = getWeek(c);
int price = 0;
if (week <= 5) { // 周一到周五的价格计算
if (c.startClock >= 9 && c.startClock <= 12) {
if (c.endClock >=9 && c.endClock <= 12) {
price = (c.endClock - c.startClock) * workDayPrice[0];
} else if (c.endClock >12 && c.endClock <= 18) {
price = (12 - c.startClock) * workDayPrice[0] + (c.endClock - 12) * workDayPrice[1];
} else if (c.endClock >18 && c.endClock <= 20) {
price = (12 - c.startClock) * workDayPrice[0] + (18 - 12) * workDayPrice[1] 
+ (c.endClock - 18) * workDayPrice[2];
} else if (c.endClock > 20 && c.endClock <= 22) {
price = (12 - c.startClock) * workDayPrice[0] + (18 - 12) * workDayPrice[1] 
+ (20 - 18) * workDayPrice[2] + (c.endClock - 20) * workDayPrice[3];
}

else if  (c.startClock > 12 && c.startClock <= 18){
if (c.endClock >=12 && c.endClock <= 18) 
price = (c.endClock - c.startClock) * workDayPrice[1];
else if (c.endClock >18 && c.endClock <= 20) 
price = (18 - c.startClock) * workDayPrice[1] 
+ (c.endClock - 18) * workDayPrice[2];
else if (c.endClock > 20 && c.endClock <= 22) 
price = (18 - c.startClock) * workDayPrice[1] + (20 - 18) * workDayPrice[2]
+ (c.endClock - 20) * workDayPrice[3];
}
else  if (c.startClock > 18 && c.startClock <= 20) {
if (c.endClock >=18 && c.endClock <= 20)
price = (c.endClock - c.startClock) * workDayPrice[2];
else if (c.endClock > 20 && c.endClock <= 22) {
price = (20 - c.startClock) * workDayPrice[2] + (c.endClock - 20) * workDayPrice[3];
}
}
else if (c.startClock > 20 && c.startClock <= 22) {
price = (c.endClock - c.startClock) * workDayPrice[3];
}

else {
if (c.startClock >= 9 && c.endClock <=12) {
if(c.endClock > 9 && c.endClock <= 12) {
price = (c.endClock - c.startClock) * weekDayPrice[0];
} else if (c.endClock > 12 && c.endClock <=18) {
price = (12 - c.startClock) * weekDayPrice[0] + (c.endClock - 12) * weekDayPrice[1];
} else if (c.endClock > 18 && c.endClock <= 22) {
price = (12 - c.startClock) * weekDayPrice[0] + (18 - 12) * weekDayPrice[1]
+ (c.endClock - 18) * weekDayPrice[2];
}
} else if (c.startClock > 12 && c.startClock <= 18) {
if (c.endClock > 12 && c.endClock <= 18)
price = (c.endClock - c.startClock) * weekDayPrice[1];
else if (c.endClock > 18 && c.endClock <= 22) 
price = (18 - c.startClock) * weekDayPrice[1] + (c.endClock - 18) * weekDayPrice[2];
} else if (c.startClock > 18 && c.startClock <= 22) {
price = (c.endClock - c.startClock) * weekDayPrice[2];
}
}
return price;
}
public static void printInvalidBookError() {
System.out.println("Error: the booking is invalid!");
}
public static void printConflictError(){
System.out.println("Error: the booking conflicts with existing bookings!");
}
public static void printConcelError() {
System.out.println("Error: the booking being cancelled does not exist!");
}
public static void printBookSuccess(){
System.out.println("Success: the booking is accepted!");
}
}


编辑于 2018-04-02 14:52:33 回复(9)
// ConsoleApplication4.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>
#include <algorithm>

using namespace std;

struct  BookInfo
{     string User;     string Date;     int StartHour;     int EndHour;     char Place;     bool IsCancel = false;     int fee = 0;     float CancelFee = 0.5;     bool operator==(BookInfo& other)     {         return User == other.User&&Date == other.Date&&StartHour == other.StartHour&&EndHour == other.EndHour&&Place == other.Place;     }     bool operator>(BookInfo& other)     {         return Date>other.Date||(Date==other.Date&&StartHour>other.StartHour);     }     bool operator<(BookInfo& other)     {         return Date < other.Date || (Date == other.Date&&StartHour < other.StartHour);     }     void printself()     {         cout << User << " " << Date << " " << StartHour << ":00~" << EndHour << ":00 " << Place << " " <<(IsCancel?"违约金":"") <<fee << "元"<<endl;     }
};

BookInfo temp;
vector<BookInfo> A;
vector<BookInfo> B;
vector<BookInfo> C;
vector<BookInfo> D;

int getWeekday(int y, int m, int d)
{     if (m<=2)     {         m += 12;         y -= 1;     }     int weekday = (d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400) % 7+1;     return weekday;
}

void getWordFromLine(const char* &date, char* buff, int &bit,int len)
{     for (int i = 0; bit <= len; bit++, i++)     {         if (date[bit] != ' ')         {             buff[i] = date[bit];         }         else         {             buff[i] = '\0';             break;         }     }
}

bool CheckValideHour(int Hour)
{     return Hour >= 9 && Hour <= 22;
}

void CancelBooking(vector<BookInfo> &A,BookInfo& info)
{     bool found = false;     for (auto& i:A)     {         if (i==info)         {             if (i.IsCancel==false)             {                 i.IsCancel = true;                 i.fee *= i.CancelFee;                 cout << "Cancel Success" << endl;             }             else             {                 cout << "Err this booking is already canceled" << endl;             }             found = true;             break;         }     }     if (!found)     {         cout << "no booking match" << endl;     }
}

void CheckAndAddBooking(vector<BookInfo> &A, BookInfo& info)
{     for (auto i:A)     {         if (i.IsCancel==false&&i.Date==info.Date)         {             if (info.StartHour>=i.StartHour&&info.StartHour<=i.EndHour)             {                 cout << "start hour unusable" << endl;                 return;             }             if (info.EndHour >= i.StartHour&&info.EndHour <= i.EndHour)             {                 cout << "end hour unusable" << endl;                 return;             }         }     }     const char* date = info.Date.c_str();     int y = atoi(date);     int m = atoi(&date[5]);     int d = atoi(&date[8]);     int week = getWeekday(y, m, d);     if (week >= 6)     {         info.fee = ((12 - info.StartHour) < 0 ? 0 : (12 - info.StartHour) * 40) + ((18 - info.StartHour) < 0 ? 0 : (18 - info.StartHour) > 6 ?6*50 : (18 - info.StartHour) * 50) +((22 - info.StartHour) < 0 ? 0 : (22 - info.StartHour) > 4 ? 4*60 : (22 - info.StartHour) * 60)             - ((12 - info.EndHour) < 0 ? 0 : (12 - info.EndHour) * 30) - ((18 - info.EndHour) < 0 ? 0 : (18 - info.EndHour) > 6 ? 6*50 : (18 - info.EndHour) * 50) -((22 - info.EndHour) < 0 ? 0 : (22 - info.EndHour) > 4 ? 4*60 : (22 - info.EndHour) * 60);         info.CancelFee = 0.25;     }     else     {         info.fee = ((12 - info.StartHour) < 0 ? 0 : (12 - info.StartHour) * 30) + ((18 - info.StartHour) < 0 ? 0 : (18 - info.StartHour)>6?6:(18 - info.StartHour) * 50) + ((20 - info.StartHour) < 0 ? 0 : (20 - info.StartHour)>2?2*80:(20 - info.StartHour) * 80) + ((22 - info.StartHour) < 0 ? 0 : (22 - info.StartHour)>2?2*60:(22 - info.StartHour) * 60)             - ((12 - info.EndHour) < 0 ? 0 : (12 - info.EndHour) * 30) - ((18 - info.EndHour) < 0 ? 0 : (18 - info.EndHour)>6?6*50:(18 - info.EndHour) * 50) - ((20 - info.EndHour) < 0 ? 0 : (20 - info.EndHour)>2?2*80:(20 - info.EndHour) * 80) - ((22 - info.EndHour) < 0 ? 0 : (22 - info.EndHour)>2?2*60:(22 - info.EndHour) * 60);     }     A.push_back(info);     sort(A.begin(), A.end());     cout << "success booking" << endl;
}
bool CheckInput(string input)
{     //U001 2016-06-02 20:00~22:00 A     char buff[128];     int bit = 0;     const char* date = input.c_str();     int len = input.length();     //user     getWordFromLine(date, buff, bit, len);     if (buff[0]=='\0')     {         cout << "no user" << endl;         return false;     }     else     {         temp.User = buff;     }     //date     bit++;     getWordFromLine(date, buff, bit, len);     if (buff[0] == '\0')     {         cout << "no Date" << endl;         return false;     }     else     {         temp.Date = buff;     }     //hour     bit++;     getWordFromLine(date, buff, bit, len);     if (buff[0] == '\0')     {         cout << "no Hour" << endl;         return false;     }     else     {         temp.StartHour = atoi(&buff[0]);         if (!CheckValideHour(temp.StartHour))         {             cout << "err start hour";             return false;         }                  int i = 0;         while (buff[i]!='~')         {             i++;         }         i++;         temp.EndHour = atoi(&buff[i]);         if (!CheckValideHour(temp.EndHour))         {             cout << "err end hour";             return false;         }         if (temp.StartHour>=temp.EndHour)         {             cout << "err start and end hour";             return false;         }     }     //place     bit++;     getWordFromLine(date, buff, bit, len);     if (buff[0] == '\0')     {         cout << "no place" << endl;         return false;     }     else     {         if (buff[1]!='\0')         {             cout << "err place";             return false;         }         else         {             temp.Place = buff[0];         }     }     if (date[bit-1]=='\0')//no Cancel     {         if (temp.Place == 'A')         {             CheckAndAddBooking(A,temp);         }         else if (temp.Place == 'B')         {             CheckAndAddBooking(B, temp);         }         else if (temp.Place == 'C')         {             CheckAndAddBooking(C, temp);         }         else if (temp.Place == 'D')         {             CheckAndAddBooking(D, temp);         }     }     else     {         //cancel         bit++;         getWordFromLine(date, buff, bit, len);         if (buff[0]!='C'||buff[1] != '\0')         {             cout << "err cancel" << endl;             return false;         }         else         {             if (temp.Place == 'A')             {                 CancelBooking(A,temp);             }             else if (temp.Place == 'B')             {                 CancelBooking(B, temp);             }             else if (temp.Place == 'C')             {                 CancelBooking(C, temp);             }             else if (temp.Place == 'D')             {                 CancelBooking(D, temp);             }         }     }          return true;
}

void DealInput(string input)
{     if (input=="")     {         int fA=0, fB=0, fC=0,fD=0, fT=0;         cout << "收入汇总" << endl;//List         cout << "---" << endl;         cout << "A" << endl;         for (auto i:A)         {             i.printself();             fA += i.fee;         }         cout << "小计:" << fA << "元" << endl << endl;         cout << "B" << endl;         for (auto i : B)         {             i.printself();             fB += i.fee;         }         cout << "小计:" << fB << "元" << endl << endl;         cout << "C" << endl;         for (auto i : C)         {             i.printself();             fC += i.fee;         }         cout << "小计:" << fC << "元" << endl << endl;         cout << "D" << endl;         for (auto i : D)         {             i.printself();             fD += i.fee;         }         cout << "小计:" << fD << "元" << endl ;         cout << "---" << endl;         fT = fA + fB + fC + fD;         cout << "总计:" << fT << "元"<<endl;     }     else     {         if (CheckInput(input))         {                      }         else         {             cout << "input error" << endl;         }     }
}
int main()
{     string input = "";     while (getline(cin, input))     {         DealInput(input);     }     system("pause");     return 0;
}


发表于 2018-03-14 18:25:00 回复(0)
import re
import datetime

def computed(date, s, e):
    Weekday = int(datetime.datetime.strptime(date,'%Y-%m-%d').strftime("%w"))
    price = 0
    if 0 < Weekday < 6:
        for i in range(s, e):
            if 9 <= i < 12:
                price += 30
            elif 12 <= i < 18:
                price += 50
            elif 18 <= i < 20:
                price += 80
            elif 20 <= i < 22:
                price += 60
    else:
        for i in range(s, e):
            if 9 <= i < 12:
                price += 40
            elif 12 <= i < 18:
                price += 50
            elif 18 <= i < 22:
                price += 60
    return price

rex = r'(?P<uid>U\d{0,5}) (?P<date>\d{0,4}-\d{0,2}-\d{0,2}) (?P<stime>\d{0,2}):00~(?P<etime>\d{0,2}):00 (?P<adr>[A-Za-z])'
rex2 = r'(?P<uid>U\d{0,5}) (?P<date>\d{0,4}-\d{0,2}-\d{0,2}) (?P<stime>\d{0,2}):00~(?P<etime>\d{0,2}):00 (?P<adr>[A-Za-z]) C'
money_arr = {}
booking_dict = {}

while True:
    s = input()
    if s == "收入汇总":
        out = '收入汇总\n------\n\n'
        total = 0
        for i in money_arr:
            out += "场地%s\n\n" % i
            out += "\n".join(list(map(lambda x:"%s  %s:00~%s:00  %s %s元" % (x['date'], x['stime'], x['etime'], "违约金" if x['state'] == 2 else "", x['price']), money_arr[i])))
            out += "\n小计: %s元\n\n" % sum(list(map(lambda x:int(x['price']), money_arr[i])))
            total += sum(list(map(lambda x:int(x['price']), money_arr[i])))
        out += "\n\n\n总计: %s元" % total
        print(out)
        continue
    m = re.match(rex2, s)
    if m:
        d = m.groupdict()
        d['stime'], d['etime'], d['state'] = int(d['stime']), int(d['etime']), 1
        d['price'] = computed(d['date'], d['stime'], d['etime'])
        if 9 > d['stime'] or d['etime'] > 22 or d['stime'] == d['etime']:
            print("预定失败! 不在营业时间段")
            break
        if d['adr'] in money_arr and d in money_arr[d['adr']]:
            money_arr[d['adr']].remove(d)
            for i in range(d['stime'], d['etime']):
                booking_dict[d['date']].remove(i)
            Weekday = int(datetime.datetime.strptime(d['date'],'%Y-%m-%d').strftime("%w"))
            if 0 < Weekday < 6:
                d['price'] = int(d['price']/2)
            else:
                d['price'] = int(d['price']/4)
            d['state'] = 2
            money_arr[d['adr']].append(d)
            print("取消预定! 用户:%s , 日期: %s, 预定时间段: %s:00~%s:00, 场地: %s" % (d['uid'], d['date'], d['stime'], d['etime'], d['adr']))
        else:
            print("取消失败! 没有找到预定订单")
        
    else:
        m = re.match(rex, s)
        if m:
            d = m.groupdict()
            d['stime'], d['etime'], d['state'] = int(d['stime']), int(d['etime']), 1
            if 9 > d['stime'] or d['etime'] > 22 or d['stime'] == d['etime']:
                print("预定失败! 不在营业时间段")
                continue
            if booking_dict.get(d['date'], None):
                tmp_arr = []
                for i in range(d['stime'], d['etime']):
                    tmp_arr.append(i)
                    if i in booking_dict[d['date']]:
                        print("预定失败! 时间段已被预定")
                        break
                else:    
                    booking_dict[d['date']].extend(tmp_arr)
                    d['price'] = computed(d['date'], d['stime'], d['etime'])
                    if d['adr'] in money_arr:
                        money_arr[d['adr']].append(d)
                    else:
                        money_arr[d['adr']] = [d]
                    print("预定场地      用户:%s , 日期: %s, 预定时间段: %s:00~%s:00, 场地: %s, 消费: %s" % (d['uid'], d['date'], d['stime'], d['etime'], d['adr'], d['price']))
            else:
                booking_dict[d['date']] = []
                for i in range(d['stime'], d['etime']):
                    booking_dict[d['date']].append(i)
                d['price'] = computed(d['date'], d['stime'], d['etime'])
                if d['adr'] in money_arr:
                    money_arr[d['adr']].append(d)
                else:
                    money_arr[d['adr']] = [d]
                print("预定场地      用户:%s , 日期: %s, 预定时间段: %s:00~%s:00, 场地: %s, 消费: %s" % (d['uid'], d['date'], d['stime'], d['etime'], d['adr'], d['price']))

        else:
            print("格式错误!")

发表于 2018-12-15 14:53:07 回复(1)
看着别人说好简单,捂脸。。
发表于 2018-07-27 13:31:00 回复(0)
用链表创建预订分别为用户 日期 时间 场地 是否预订。设置总金额为零。场地设置为booblean,true就是预订。日期可以设置为一个类,时间段设置为属性,价格设置为方法。输出属性值有且仅有一个。日期设置为字符串,用来做对比,相同日期才需要判断时间类属性,不同日期则不需要。布尔值的每一次改变调用时间方法。增加总金额度。
发表于 2018-07-26 16:56:30 回复(4)
import numpy as np
import datetime
def orderInput():
    order = "0"
    orderLists = []
    while True:
        order = input()
        if order == '':
            break

        if order[4] != ' ':
            print("Error: the booking is invalid!")
            continue

        orderList = order.split(" ")
        if len(orderList)==4:
            orderList.append("D")

        ## 设置为默认不打折
        orderList.append('10')

        ## 判断时间是否合法
        orderTime = orderList[2].split("~")
        orderList[2] = orderTime
        ST1 = orderTime[0]
        ET1 = orderTime[1]
        st = ST1.split(":")
        et = ET1.split(":")
        if (st[1] != "00" or et[1] != "00" or int(st[0])22 or int(et[0])>22 or int(st[0]) >= int(et[0])):
            print("Error: the booking is invalid!")
            continue

        # 判断场馆是否合法
        orderPlace = orderList[3]
        if (orderPlace not in ("A", "B", "C", "D")):
            print("Error: the booking is invalid!")
            continue

        cancelFlag = orderList[4]
        timeConFlag = False
        MatchFlag = False
        ## 判断时间是否冲突
        if (cancelFlag != "C"):
            for items in orderLists:
                if items[4] == "C":
                    continue
                T2 = items[2]
                ST2 = T2[0]
                ET2 = T2[1]
                st2 = ST2.split(":")
                et2 = ET2.split(":")
                timeConFlag = ( isTimeConflict(st, et, st2, et2) and isEqual(orderList[1], items[1]) and isEqual(orderList[3], items[3]) )
                if timeConFlag:
                    print("Error: the booking conflicts with existing bookings!")
                    break
        ## 判断是否取消订单
        else:
            for items in orderLists:
                if ( isEqual(items[0],orderList[0]) and isEqual(items[1],orderList[1]) and isEqual(items[2],orderList[2]) and isEqual(items[3],orderList[3]) and items[4]!="C"):
                    items[4] = "C"
                    print("Success: the booking is accepted!") 
                    MatchFlag = True
                    break
            if not MatchFlag:
                print("Error: the booking being cancelled does not exist!")
        ## 判断是否打折
        lines = readDiscount()
        for line in lines:
            if (line[0:10] = orderList[1]):
                orderList[5] = line[22]

        if (not timeConFlag) and (cancelFlag != "C"):    
            orderLists.append(orderList)  
            print("Success: the booking is accepted!")
    return orderLists
def readDiscount():
    f = open("./discount.txt","r")
    lines = f.readlines()
    return lines
def isEqual(v1, v2):
    if v1 == v2:
        return True
    else:
        return False

def isTimeConflict(st1, et1, st2, et2):
    if not (et1<=st2 or et2<=st1) :
        return True
    else:
        return False

def dayOfWeek(date):
    date = date.split("-")
    year = int(date[0])
    month = int(date[1])
    day = int(date[2])
    anyday=datetime.datetime(year,month,day).strftime("%w")
    return anyday
def calFare(date,time,cancelFlag,discount):
    ST = time[0].split(":")
    ET = time[1].split(":")
    st = int(ST[0]) - 9
    et = int(ET[0]) - 9
    fareListofWD = np.array([30,30,30,50,50,50,50,50,50,80,80,60,60])
    fareListofWE = np.array([40,40,40,50,50,50,50,50,50,60,60,60,60])
    day = dayOfWeek(date)
    if day in ('6', '7'):
        fare = sum(fareListofWE[st:et]) * int(discount)/10
        cutoff = sum(fareListofWE[st:et]) - fare
        if cancelFlag == 'C':
            fare = fare/4
    else:
        fare = sum(fareListofWD[st:et]) * int(discount)/10
        cutoff = sum(fareListofWD[st:et]) - fare
        if cancelFlag == 'C':
            fare = fare/2
    return int(fare), int(cutoff)
def printFareP(orderLists, place):
    groundFare = 0
    orderListsP, countP = findPlaceOrder(orderLists, place)
    idxP = sortOrderLists(orderListsP)
    for index in idxP:
        items = orderListsP[index]
        timeT = items[2]
        if items[4] == 'C':
            fare, cutoff = calFare(items[1],items[2],items[4],items[5])
            #print(items[1],timeT[0],'~',timeT[1],"违约金",fare,"元")
            print('{} {}{}{} {} {}{}'.format(items[1],timeT[0],'~',timeT[1],"违约金",fare,"元"))
        else:
            fare, cutoff = calFare(items[1],items[2],items[4],items[5])
            if items[5] == '10':
                print('{} {}{}{} {}{}'.format(items[1],timeT[0],'~',timeT[1],fare,"元"))
                #print(items[1],timeT[0],'~',timeT[1],fare,"元")
            else:
                print('{} {}{}{} {}{} {}{}{}'.format(items[1],timeT[0],'~',timeT[1],fare,"元","已优惠:",cutoff,"元"))
                #print(items[1],timeT[0],'~',timeT[1],fare,"元","已优惠:",cutoff,"元")
        groundFare += fare
    return groundFare

def printFare(orderLists):
    totalFare = 0    
    print('收入汇总')
    print('---')    
    print('场地:A')
    groundFare = printFareP(orderLists, 'A')
    totalFare += groundFare
    print('{} {}{}'.format('小计:', groundFare, '元'))
    #print('小计:', groundFare, '元')
    print('\n')
    print('场地:B')
    groundFare = printFareP(orderLists, 'B')
    totalFare += groundFare
    print('{} {}{}'.format('小计:', groundFare, '元'))
    print('\n')
    print('场地:C')
    groundFare = printFareP(orderLists, 'C')
    totalFare += groundFare
    print('{} {}{}'.format('小计:', groundFare, '元'))
    print('\n')
    print('场地:D')
    groundFare = printFareP(orderLists, 'D')
    totalFare += groundFare
    print('{} {}{}'.format('小计:', groundFare, '元'))
    print('---')
    #print('总计:', totalFare, '元')
    print('{} {}{}'.format('总计:', totalFare, '元'))
def findPlaceOrder(orderLists, place):
    orderListsP = []
    countP = 0
    for items in orderLists:
        if items[3] == place:
            orderListsP.append(items)
            countP += 1
    return orderListsP, countP

def sortOrderLists(orderListsP):
    arrayP = []
    index = 0
    for items in orderListsP:
        tempD = items[1]
        tempT = items[2]
        tempST = tempT[0]
        strP = tempD[0:4] + tempD[5:7] + tempD[8:10] + tempST[0:2]
        arrayP.append(int(strP)) 
        index =  index+1
    #npList = np.array(orderListsP)
    idx = np.argsort(arrayP[:], axis = 0)
    return idx

if __name__ == '__main__':


    # 测试
    # date = "2018-07-25"       
    # print(dayOfWeek(date))

    orderLists = orderInput()
    printFare(orderLists)
发表于 2018-07-26 16:35:41 回复(0)
验证合法性 判定是否冲突 处理取消 便利求和
发表于 2018-05-28 17:52:04 回复(0)
/**
 * 小明是一个羽毛球场馆的管理员,管理着四个羽毛球场地(A,B,C,D场地),负责场地的维护和预订工作。为了简化自己的工作,场地只接受整点预订,预订以小时为单位。
 
    羽毛球场的收费标准如下:

    周一到周五:
    9:00 ~ 12:00 30元/时
    12:00 ~ 18:00 50元/时
    18:00 ~ 20:00 80元/时
    20:00 ~ 22:00 60元/时
    周六及周日
    9:00 ~ 12:00 40元/时
    12:00 ~ 18:00 50元/时
    18:00 ~ 22:00 60元/时
    羽毛球场馆在预订之后,可以接受取消预订,不过取消预订需要交违约金,违约金的计算规则如下:

    周一到周五的预订取消收取全部费用的50%作为违约金
    周六周日的预订取消收取全部费用的25%作为违约金
    由于手头还有其他工作,小明希望能够借助计算机程序来自动化处理预订及取消预订的事务,并且希望程序能够打印出场馆的收入汇总情况。

    程序输入
    预订:用户预订以字符串的形式输入,一行字符串代表一个预定

    格式为{用户ID} {预订日期 yyyy-MM-dd} {预订时间段 HH:mm~HH:mm} {场地},如U123 2016-06-02 20:00~22:00 A,代表用户U123预定2016年06月02日晚上20:00到22:00的场地A的时间段
    时间段的起止时间必然为整小时,否则报错
    如预订与已有预订冲突,也会报错
    取消预定:用户取消预定,输入也以一行字符串的形式表现

    格式为{用户ID} {预订日期 yyyy-MM-dd} {预订时间段 HH:mm~HH:mm} {场地} {取消标记},如U123 2016-06-02 20:00~22:00 A C,代表用户U123取消其在2016年06月02日晚上20:00到22:00在场地A的预订,其中取消标记C代表Cancel
    取消标记只能是C,若为其他字符则报错
    时间段的起止时间必然为整小时,否则报错
    只能完整取消之前的预订,不能取消部分时间段
    取消预订的请求,必须与之前的预订请求严格匹配,需要匹配的项有用户ID,预订日期,预订时间段,场地
    打印场馆收入汇总: 将所有的预订和取消预订带来的收入汇总信息打印出来

    格式为,输入一个空行,代表打印收入汇总
 */
const _ = require('lodash');
const moment = require('moment');

process.stdin.setEncoding('utf8');

const bookingErrorMsg = '> Error: the booking is invalid!\n';
const bookingSuccessMsg = '> Success: the booking is accepted!\n';
const cancelErrorMsg = '> Error: the booking being cancelled does not exist!\n'
const bookingConfilictsMsg = '> Error: the booking conflicts with existing bookings!\n'
const courtBookingRecs = [];

const discountArr = [
  {
    startDate: '2016-04-01',
    endDate: '2016-04-02',
    rate: 6,
  }, {
    startDate: '2017-08-01',
    endDate: '2017-08-03',
    rate: 8, 
  }
]

const betweenMondayAndFridayPrice = [
  {
    startTime: 9,
    endTime: 12,
    price: 30,
  }, {
    startTime: 12,
    endTime: 18,
    price: 50,
  }, {
    startTime: 18,
    endTime: 20,
    price: 80,
  }, {
    startTime:20,
    endTime: 22,
    price: 60,
  }
]

const weekendsPrice = [{
    startTime: 9,
    endTime: 12,
    price: 40,
  }, {
    startTime: 12,
    endTime: 18,
    price: 50,
  }, {
    startTime: 18,
    endTime: 22,
    price: 60,
  }
]

process.stdin.on('readable', () => {
  const chunk = process.stdin.read();
  if (chunk !== null) {
    const chunkArr = typeof chunk === 'string' ? chunk.split(' ') : [];
    if (chunkArr.length === 1 && chunkArr[0] === '\n') {
      printBooking();
    } else if (chunkArr.length === 4) {
      bookingBadminitonCourt(chunkArr);
    } else if (chunkArr.length === 5 && chunkArr[4] === 'C\n') {
      cancelBookedCourt(chunkArr);
    } else {
      process.stdout.write(bookingErrorMsg); 
    }
  }
});

function printBooking() {
  process.stdout.write('收入汇总\n---\n');
  let allCourtTotalPrice = 0;
  const courtBookingRecsGroupTemp = _.groupBy(courtBookingRecs, 'courtNo');
  let courtBookingRecsGroup = {
    A: courtBookingRecsGroupTemp['A'] || [],
    B: courtBookingRecsGroupTemp['B'] || [],
    C: courtBookingRecsGroupTemp['C'] || [],
    D: courtBookingRecsGroupTemp['D'] || [],
  };

  _.map(courtBookingRecsGroup, (bookingRecs, courtNo) => {
    process.stdout.write(`场地: ${courtNo}\n`);
    let oneCourtTotalPrice = 0;
    _.map(bookingRecs, (rec) => {
      let recTemp = rec;
      recTemp.isDiscount = false;
      recTemp.discountedPrice = 0;
      let discountPlan = _.find(discountArr, (discount) => {
        return moment(rec.date).isSameOrAfter(discount.startDate) && moment(rec.date).isSameOrBefore(discount.endDate)
      });
      if (!_.isUndefined(discountPlan)) {
        recTemp.isDiscount = true;
        if (recTemp.isReturn) {
          recTemp.discountedPrice = recTemp.returnPay -  Math.round(recTemp.returnPay * (discountPlan.rate / 10)); 
        } else {
          recTemp.discountedPrice = recTemp.bookingPrice - Math.round(recTemp.bookingPrice * (discountPlan.rate / 10));
        }
      }
      if (recTemp.isReturn) {
        oneCourtTotalPrice += recTemp.returnPay - recTemp.discountedPrice;
      } else {
        oneCourtTotalPrice += recTemp.bookingPrice - recTemp.discountedPrice;
      }

      process.stdout.write(`${[
          recTemp.UID, recTemp.date,
          [recTemp.startTime, recTemp.endTime].join('~'),
          recTemp.isReturn ? `违约金 ${recTemp.returnPay - recTemp.discountedPrice}元` : `${rec.bookingPrice - recTemp.discountedPrice}元`,
          recTemp.isDiscount ? `已优惠: ${recTemp.discountedPrice}元` : '',
        ].join(' ')}\n`);
    });
    process.stdout.write(`小计: ${oneCourtTotalPrice}元\n\n`);
    allCourtTotalPrice += oneCourtTotalPrice;
  });
  process.stdout.write(`---\n总计: ${allCourtTotalPrice}元\n\n`); 
}

function cancelBookedCourt(chunkArr) {
  const cancelRecStr = chunkArr.slice(0, 4).join(' ');
  let isCancelSuccess = false;
  for (let i = 0, len = courtBookingRecs.length; i < len; i++) {
    let bookingRec = courtBookingRecs[i];
    let bookingRecStr = [bookingRec.UID, bookingRec.date, [bookingRec.startTime, bookingRec.endTime].join('~'), bookingRec.courtNo].join(' ');
    if (bookingRecStr === cancelRecStr && !bookingRec.isReturn) {
      const week = moment(bookingRec.date).isoWeekday();
      bookingRec.returnPay = [6, 7].indexOf(week) < 0 ? bookingRec.bookingPrice * 0.5 : bookingRec.bookingPrice * 0.25;
      bookingRec.isReturn = true;
      isCancelSuccess = true;
      break;
    }
  }
  process.stdout.write(isCancelSuccess ? bookingSuccessMsg : cancelErrorMsg) 
}

function bookingBadminitonCourt(chunkArr) {
  const UID = chunkArr[0];
  const bookingDate = chunkArr[1];
  const bookingTimePeriod = chunkArr[2].split('~');
  const bookingStartTime = bookingTimePeriod[0];
  const bookingEndTime = bookingTimePeriod[1];
  const bookingCourtNo = chunkArr[3].substring(0, 1);
 
  if (isBookingVerifyPassed(bookingDate, bookingStartTime, bookingEndTime, bookingCourtNo)){
    const isBookingSuccess = bookingCourt(UID, bookingCourtNo, bookingDate, bookingStartTime, bookingEndTime);
    return process.stdout.write(isBookingSuccess ? bookingSuccessMsg : bookingConfilictsMsg);
  }
  return process.stdout.write(bookingErrorMsg);
}

function isBookingVerifyPassed(bookingDate, bookingStartTime, bookingEndTime, bookingCourtNo){
  const standBookingTimePeriod = ['09:00', '22:00'];
  const bookingStartDateTime = moment([bookingDate, bookingStartTime].join(' '));
  const bookingEndDateTime = moment([bookingDate, bookingEndTime].join(' '));
  const comparedStartDateTime = moment([bookingDate, standBookingTimePeriod[0]].join(' '));
  const comparedEndDateTime = moment([bookingDate, standBookingTimePeriod[1]].join(' '));
  if (bookingStartDateTime.isBefore(comparedStartDateTime)
     || bookingEndDateTime.isAfter(comparedEndDateTime)
     || bookingEndDateTime.isSameOrBefore(bookingStartDateTime)
     || bookingStartTime.split(':')[1] !== '00'
     || bookingEndTime.split(':')[1] !== '00'
     || ['A', 'B', 'C', 'D'].indexOf(bookingCourtNo) < 0) {

    return false;
  }
  return true; 
}

function bookingCourt(UID, courtNo, date, startTime, endTime) {
  const bookingStartDateTime = moment([date, startTime].join(' ')); 
  const bookingEndDateTime = moment([date, startTime].join(' '));
  let isBookingConflic = false;
  for (let i = 0, len = courtBookingRecs.length; i < len; i++) {
    let bookingRec = courtBookingRecs[i];
    let comparedStartDateTime = moment([bookingRec.date, bookingRec.startTime].join(' '));
    let comparedEndDateTime = moment([bookingRec.date, bookingRec.endTime].join(' '));
    if ((bookingRec.courtNo === courtNo) && !bookingRec.isReturn
      && (bookingStartDateTime.isSameOrAfter(comparedStartDateTime)
      || bookingEndDateTime.isSameOrBefore(comparedEndDateTime))) {
      isBookingConflic = true;
      break;   
    }
  }
  if (isBookingConflic) {
    return false;
  }
  const bookingPrice = getBookingPrice(date, startTime, endTime);
  courtBookingRecs.push({
    UID,
    date,
    courtNo,
    endTime,
    startTime,
    bookingPrice,
    returnPay: 0,
    isReturn: false,
  });
  return true;
}

function getBookingPrice(date, startTime, endTime) {
  const week = moment(date).isoWeekday();
  let startHour = startTime.split(':')[0];
  let endHour = endTime.split(':')[0];
  let bookingPrice = 0;
  if (1 <= week && week <= 5) {
    return countPrice(betweenMondayAndFridayPrice, startHour, endHour);
  }
  return countPrice(weekendsPrice, startHour, endHour);
}

function countPrice(planArr, originalStartTime, originalEndHour) {
  let startTime = originalStartTime;
  let endTime = originalEndHour;
  let bookingPrice = 0;
  _.map(planArr, (plan) => {
    if ((plan.startTime <= startTime) && (startTime < plan.endTime) && (startTime < endTime)) {
      if (plan.endTime >= endTime) {
        bookingPrice += (endTime - startTime) * plan.price;
      } else {
        bookingPrice += (plan.endTime - startTime) * plan.price;
        startTime = plan.endTime;
      }
    } 
  });
  return bookingPrice; 
}

process.stdin.on('end', () => {
  process.stdout.write('end');
});

发表于 2018-03-23 16:49:32 回复(1)
import re
import time

booking_list = []  # 用户有效输入信息的列表


def booking(booking_infos):
    """处理用户预订信息"""

    # 非整点时间预订信息的格式
    wrong_booking_str = "U\d{3}\s\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}~\d{2}:\d{2}\s[A-D]"
    # 整点时间预订信息的格式
    booking_str = "U\d{3}\s\d{4}-\d{2}-\d{2}\s\d{2}:00~\d{2}:00\s[A-D]"
    # 取消预订信息的格式
    canceling_str = booking_str + "\sC"

    pattern1 = re.compile(booking_str)
    pattern2 = re.compile(wrong_booking_str)
    pattern3 = re.compile(canceling_str)

    # 限定长度为31筛选并匹配取消预定的格式
    if ((len(booking_infos) == 31) & (re.match(pattern3, booking_infos) is not None)
            & (booking_infos[16:18] >= "09")
            & (booking_infos[16:18] < booking_infos[22:24])
            & (booking_infos[22:24] <= "22")):
        # 遍历所有有效输入,若匹配到对应的预订信息则处理取消业务,若已取消会提示
        for info in booking_list:
            if booking_infos == info + " C":
                print("> Success: the booking is accepted!")
                booking_list.remove(info)
                booking_list.append(booking_infos)
                return
            elif booking_infos == info:
                print("> Error: the booking being cancelled does not existed!")
                return

    # 限定长度为29筛选并匹配非整点时间预定的格式
    elif ((len(booking_infos) == 29) & (re.match(pattern2, booking_infos) is not None)
            & (booking_infos[16:18] >= "09")
            & (booking_infos[16:18] < booking_infos[22:24])
            & (booking_infos[22:24] <= "22")):
        # 匹配整点时间预订信息的格式
        if re.match(pattern1, booking_infos) is not None:
            # 确保用户有效输入信息的列表不为空
            if not booking_list:
                print("> Success: the booking is accepted!")
                booking_list.append(booking_infos)
                return
            # 遍历,若出现时间冲突报错;没有则处理预订信息
            for info in booking_list:
                if ((len(info) == 29)
                        & (info[5:15] + info[28] == booking_infos[5:15] + booking_infos[28])
                        & (not ((info[16:18] > booking_infos[22:24])
                                | (info[22:24] < booking_infos[16:18])))):
                    print("> Error: the booking conflicts with existing bookings!")
                    return
                else:
                    print("> Success: the booking is accepted!")
                    booking_list.append(booking_infos)
                    return
        else:
            print("> Error: time needs to start and end with the whole time!")
            return

    # 输入长度不符或格式不对就报错
    else:
        print("> Error: the booking is invalid!")
        return


def fweekdays(t):
    """工作日收费的不定积分函数"""

    fee: int

    if (t >= 9) & (t <= 12):
        fee = (t - 9) * 30
    elif (t > 12) & (t <= 18):
        fee = (t - 12) * 50 + 90
    elif (t > 18) & (t <= 20):
        fee = (t - 18) * 80 + 390
    elif (t > 20) & (t <= 22):
        fee = (t - 20) * 60 + 550

    return fee


def fweekends(t):
    """周末收费的不定积分函数"""

    fee: int

    if (t >= 9) & (t <= 12):
        fee = (t - 9) * 40
    elif (t > 12) & (t <= 18):
        fee = (t - 12) * 50 + 120
    elif (t > 18) & (t <= 22):
        fee = (t - 18) * 60 + 420

    return fee


def bill_calculating(booking_str):
    """计算收费情况,返回单次费用与对应取消时的比率"""

    # 获取订单日期
    booking_time = time.strptime(booking_str[0:10], "%Y-%m-%d")
    start_time = int(booking_str[11:13])  # 订单的开始时间
    end_time = int(booking_str[17:19])  # 订单结束的时间
    bill: int  # 收费
    ratio: float  # 对应取消时的比率

    # 计算单场收费结果,按周末与工作日区分
    if (booking_time.tm_wday == 5) | (booking_time.tm_wday == 6):
        ratio = 0.25
        bill = fweekends(end_time) - fweekends(start_time)
    else:
        ratio = 0.5
        bill = fweekdays(end_time) - fweekdays(start_time)

    return [bill, ratio]


def printing_bill(list, char):
    """打印单场收入汇总并返回该场地收入总额"""

    bill_of_court = []  # 去用户ID后根据场地划分的用户预订信息列表
    for info in list:
        if info[28] == char:
            bill_of_court.append(info[5:])
    # 升序排序
    bill_of_court = sorted(bill_of_court)
    print("> 场地:%s" % char)
    count = 0  # 单笔费用
    # 遍历,打印单笔收费情况和小计
    for info in bill_of_court:
        bill, ratio = bill_calculating(info)
        if len(info) == 24:
            print("> " + info[0:22] + " " + str(bill) + "元")
            count += bill
        else:
            print("> " + info[0:22] + " 违约金 " + str(bill * ratio) + "元")
            count += bill * ratio
    print("> 小计:%.1f" % count)
    if char == "D":
        print("> ---")
    else:
        print(">")
    return count


while True:

    # 接受用户预订信息
    booking_info = input()

    # 判断输入是否为空行,否就处理预订信息,是就打印收入汇总
    if booking_info != "":
        booking(booking_info)

    else:
        count_of_all = (printing_bill(booking_list, "A")
                        + printing_bill(booking_list, "B")
                        + printing_bill(booking_list, "C")
                        + printing_bill(booking_list, "D"))
        print("总计:%.1f元" % count_of_all)

发表于 2020-10-06 16:31:11 回复(0)
kkk
发表于 2018-09-04 14:27:11 回复(0)
/*******************************
* > File: badminton.cc
* > Date: 2018/08/29
* > Author: lamia
* > Rule: g++ badminton.cc -o ./gen -O2 -std=c++11 -pg -g -I./ -L./ -lglog -lgtest -pthread
* > Info: 
* [TOC]
* 
* 说明
* 本作业限时2天完成
* 可以选用擅长的语言完成,例如C、C++、Java、C#、Javascript、Python、Scala等
* 可以使用第三方库简化代码(如日期,时间、集合操作等)
* 作业的输入和输出必须和题目的测试用例输出严格一致
* 作业完成后必须附上 Readme 纯文本文档(推荐使用 markdown 排版)
* Readme文档中应描述如何运行单元测试或主程序来证明作业的正确性(至少针对测试用例输入能够得到对应输出)
* 
* 家庭作业部分
* 小明是一个羽毛球场馆的管理员,管理着四个羽毛球场地(A,B,C,D场地),负责场地的维护和预订工作。为了简化自己的工作,场地只接受整点预订,预订以小时为单位。
* 
* 羽毛球场的收费标准如下:
* 
* 周一到周五:
* 9:00 ~ 12:00 30元/时
* 12:00 ~ 18:00 50元/时
* 18:00 ~ 20:00 80元/时
* 20:00 ~ 22:00 60元/时
* 周六及周日
* 9:00 ~ 12:00 40元/时
* 12:00 ~ 18:00 50元/时
* 18:00 ~ 22:00 60元/时
* 羽毛球场馆在预订之后,可以接受取消预订,不过取消预订需要交违约金,违约金的计算规则如下:
* 
* 周一到周五的预订取消收取全部费用的50%作为违约金
* 周六周日的预订取消收取全部费用的25%作为违约金
* 由于手头还有其他工作,小明希望能够借助计算机程序来自动化处理预订及取消预订的事务,并且希望程序能够打印出场馆的收入汇总情况。
* 
* 程序输入
* 预订:用户预订以字符串的形式输入,一行字符串代表一个预定
* 
* 格式为{用户ID} {预订日期 yyyy-MM-dd} {预订时间段 HH:mm~HH:mm} {场地},如U123 2016-06-02 20:00~22:00 A,代表用户U123预定2016年06月02日晚上20:00到22:00的场地A的时间段
* 时间段的起止时间必然为整小时,否则报错
* 如预订与已有预订冲突,也会报错
* 取消预定:用户取消预定,输入也以一行字符串的形式表现
* 
* 格式为{用户ID} {预订日期 yyyy-MM-dd} {预订时间段 HH:mm~HH:mm} {场地} {取消标记},如U123 2016-06-02 20:00~22:00 A C,代表用户U123取消其在2016年06月02日晚上20:00到22:00在场地A的预订,其中取消标记C代表Cancel
* 取消标记只能是C,若为其他字符则报错
* 时间段的起止时间必然为整小时,否则报错
* 只能完整取消之前的预订,不能取消部分时间段
* 取消预订的请求,必须与之前的预订请求严格匹配,需要匹配的项有用户ID,预订日期,预订时间段,场地
* 打印场馆收入汇总: 将所有的预订和取消预订带来的收入汇总信息打印出来
* 
* 格式为,输入一个空行,代表打印收入汇总
*******************************/

#include <bits/stdc++.h>
#include <gtest/gtest.h>

/************* Common Define **************/
// error code definition // 定义错误码
typedef enum {
  eOK = 0, 
  eNullptr = -1, 
  eBadRequest = -2, 
  eNotValid = -3, 
  eCanceled = -4, 
  eBooked = -5, 
  eNotFound = -6, 
  eUnknownIssue = -999, 
}ErrCode;

// time format definition // 定义时间格式
typedef struct {
  int y, m, d;
  int hstart, hend;
  int w;
}Date;

// discount definition // 定义折扣信息
typedef struct {
  Date start;
  Date end;
  int discount;
}Discount;

// rename // 重命名类型
typedef std::vector<Discount> Discounts;
typedef std::string Place; // place: "A", "B", "C", "D"
typedef std::string UserName; // user name
typedef std::string CurrentOp; // current operation: "book", "cancel", "none"
typedef std::string LastOp; // last operation: "book", "cancel", "none"
typedef float BookPrice; // money paid for booking
typedef float CancelPrice; // money paid for canceling booking
typedef std::string ShortRecord; // string stored record in thr format of "yyyy-mm-dd-HH-HH-P-UserName"

// book record definition // 定义预定记录的格式
typedef struct {
  Date date;
  Place place;
  UserName user;
  CurrentOp cop;
  LastOp lop;
  BookPrice bp;
  CancelPrice cp;
}Record;

/* list to store the record in order // 此链表用来排序预定记录
析构函数未正确delete, 因此先注释掉
*/
typedef struct ShortRecordList {
  ShortRecordList(const ShortRecord &sr): short_record(sr), head(nullptr), tail(nullptr), next(nullptr) {}
  ~ShortRecordList(void) {
    ShortRecordList *c = this, *r = nullptr;
    while(nullptr != c) {
      r = c->next;
      // fprintf(stderr, "[DEBUG], %s > delete addr: %#x, %s\n", __func__, c, c->short_record.c_str());
      // delete c;
      c = r;
    }
  }
  // 添加一条记录, 并按照场馆使用时间升序排序
  ErrCode add(const ShortRecord &sr) {
    this->tail->next = new ShortRecordList(sr);
    return this->insertByOrder(this->tail->next);
  }
  // 排序
  ErrCode insertByOrder(ShortRecordList *srl) {
    auto c = this->tail->head;
    ShortRecordList *last = c;
    while(nullptr != c) {
      if(c->short_record < srl->short_record) {last = c; c = c->next;}
      else break;
    }
    if(this->tail->head == last) {
      // fprintf(stderr, "[DEBUG], %s > srl: %s -> last: %s, \n", __func__, srl->short_record.c_str(), last->short_record.c_str());
      this->tail->head->next = srl->next;
      srl->next = this->tail->head;
      this->tail->head = srl;
    }
    else {
      // fprintf(stderr, "[DEBUG], %s > last: %s -> srl: %s, \n", __func__, last->short_record.c_str(), srl->short_record.c_str());
      last->next = srl;
      srl->head = this->tail->head;
      this->tail = srl;
    }
    if(0)
    {
      c = this->tail->head;
      fprintf(stderr, "start -> ");
      while(nullptr != c) {fprintf(stderr, "%s -> ", c->short_record.c_str()); c = c->next;}
      fprintf(stderr, "end\n");
    }
    return eOK;
  }
  ShortRecord short_record; // 短记录, 上面已定义
  ShortRecordList *head; // 链表头指针, 调用格式为 plist->tail->head
  ShortRecordList *tail; // 链表尾指针, 调用格式为 plist->tail
  ShortRecordList *next; // 用来连接链表
}ShortRecordList;

typedef std::map<ShortRecord, Record> ShortRecordMap; // 映射短记录与完整记录
/************* Common Define **************/

/************* Booker **************/
/* 预定Booker类
shop_tradeable_matrix_: float二维数组, [行/列]为[星期几/几点钟], 存放每天每个时间点的价格
*/
class Booker {
public:
  Booker(void): output_(""), sum_(0.f), places_{"A", "B", "C", "D"}, 
                workday_cancel_percent_(0.5f), 
                weekday_cancel_percent_(workday_cancel_percent_ / 2.f) {
    for(auto &p: this->places_) {
      this->place_short_records_[p] = nullptr;
      this->place_price_sum_[p] = 0.f;
    }
    this->shop_tradeable_matrix_.resize(7);
    for(int w = 0; w < 7; ++w) {
      this->shop_tradeable_matrix_[w].resize(24, 0.f);
      for(int h = 0; h < 24; ++h) {
        if(5 == w or 6 == w) {
          if(h + 1 >=  9 and h + 1 < 12) this->shop_tradeable_matrix_[w][h] = 40.f;
          if(h + 1 >= 12 and h + 1 < 18) this->shop_tradeable_matrix_[w][h] = 50.f;
          if(h + 1 >= 18 and h + 1 < 22) this->shop_tradeable_matrix_[w][h] = 60.f;
        }
        else {
          if(h + 1 >=  9 and h + 1 < 12) this->shop_tradeable_matrix_[w][h] = 30.f;
          if(h + 1 >= 12 and h + 1 < 18) this->shop_tradeable_matrix_[w][h] = 50.f;
          if(h + 1 >= 18 and h + 1 < 20) this->shop_tradeable_matrix_[w][h] = 80.f;
          if(h + 1 >= 20 and h + 1 < 22) this->shop_tradeable_matrix_[w][h] = 60.f;
        }
      }
    }
    if(0)
    {
      fprintf(stderr, "shop working time matrix:\nday\\hour");
      for(int h = 7; h < 24; ++h) {
        fprintf(stderr, "%2d\t", h + 1);
      }
      fprintf(stderr, "\n");
      for(int w = 0; w < 7; ++w) {
        fprintf(stderr, "%d\t", w + 1);
        for(int h = 7; h < 24; ++h) {
          fprintf(stderr, "%2.0f\t", this->shop_tradeable_matrix_[w][h]);
        }
        fprintf(stderr, "\n");
      }
    }
  }
  
  ~Booker(void) {
    for(auto &psr: this->place_short_records_) {
      if(nullptr != psr.second) delete psr.second->head;
    }
  }
  
  // 获取输入并处理该条记录
  const std::string getInput(const std::string &inp) {
    auto status = eNullptr;
    Record record = {0};
    ShortRecord short_record = "";
    status = this->parseRecordFromString(inp, record, short_record);
    if(eOK != status) {
      return "Error: the booking is invalid!";
    }
    // 添加/修改记录
    // fprintf(stderr, "[DEBUG] >>> \n");
    if(0 == this->short_record_map_.count(short_record)) {
      if(nullptr == this->place_short_records_[record.place]) {
        this->place_short_records_[record.place] = new ShortRecordList(short_record);
        this->place_short_records_[record.place]->head = \
        this->place_short_records_[record.place]->tail = \
        this->place_short_records_[record.place];
      }
      else this->place_short_records_[record.place]->add(short_record);
      this->short_record_map_[short_record] = record;
      // fprintf(stderr, "[DEBUG], %s > insert %s, cop: %s, lop: %s\n", \
              __func__, short_record.c_str(), \
              this->short_record_map_[short_record].cop.c_str(), record.lop.c_str());
    }
    else {
      this->short_record_map_[short_record].cop = record.cop;
      // fprintf(stderr, "[DEBUG], %s > skip %s, cop: %s, lop: %s\n", \
              __func__, short_record.c_str(), \
              this->short_record_map_[short_record].cop.c_str(),  \
              this->short_record_map_[short_record].lop.c_str());
    }
    // 处理记录
    status = this->go(short_record);
    if(eCanceled == status) {
      return "Error: the booking being cancelled does not exist!";
    }
    if(eBooked == status) {
      return "Error: the booking conflicts with existing bookings!";
    }
    else if(eOK != status){
      return "Bad return in go!";
    }
    return "Success: the booking is accepted!";
  }
  
  // 分割字符串
  const std::vector<std::string> split(const std::string &line, const std::string c = " ") {
    std::vector<std::string> v;
    std::string::size_type pos1, pos2;
    pos2 = line.find(c);
    pos1 = 0;
    while(std::string::npos != pos2) {
      v.push_back(line.substr(pos1, pos2-pos1));       
      pos1 = pos2 + c.size();
      pos2 = line.find(c, pos1);
    }
    if(pos1 != line.length()) v.push_back(line.substr(pos1));
    return v;
  }
  
  // 解析字符串到记录
  ErrCode parseRecordFromString(const std::string &line, Record &record, ShortRecord &short_record) {
    auto v = this->split(line, " ");
    if(0)
    {
      fprintf(stderr, "size: %ld\n", v.size());
      for(auto &i: v) fprintf(stderr, "%s ", i.c_str());
      fprintf(stderr, "\n");
    }
    return this->parseAndValid(v, record, short_record);
  }
  
  // 解析并验证是否为有效输入
  ErrCode parseAndValid(const std::vector<std::string> &vr, Record &record, ShortRecord &short_record) {
    if(4 != vr.size() and 5 != vr.size()) return eNotValid;
    if(5 == vr.size()) {
      if(vr[4] != "C") return eNotValid;
      else record.cop = "cancel";
    }
    else record.cop = "book";
    // user yyyy-mm-dd HH:MM~HH:MM place [cop]
    record.user = vr[0];
    auto status = this->parseDate(vr[1], vr[2], record.date);
    if(eOK != status) return status;
    record.place = vr[3];
    if(vr[3] != "A" and vr[3] != "B" and vr[3] != "C" and vr[3] != "D") return eNotValid;
    record.lop = "none";
    short_record = vr[1] + "-" + vr[2].substr(0, 2) + "-" + vr[2].substr(6, 2) + "-" + vr[3] + "-" + vr[0];
    // this->print(record);
    return eOK;
  }
  
  // 解析时间
  ErrCode parseDate(const std::string &ymd, const std::string &hm, Date &date) {
    auto v = this->split(ymd, "-");
    if(3 != v.size()) return eNotValid;
    date.y = std::stoi(v[0]);
    date.m = std::stoi(v[1]);
    date.d = std::stoi(v[2]);
    v = this->split(hm, "~");
    if(2 != v.size()) return eNotValid;
    int m = -1;
    auto starthm = this->split(v[0], ":");
    auto endhm = this->split(v[1], ":");
    if(2 != starthm.size() or 2 != endhm.size()) return eNotValid;
    m = std::stoi(starthm[1] + endhm[1]);
    if(0 != m) return eNotValid;
    date.hstart = std::stoi(starthm[0]);
    date.hend = std::stoi(endhm[0]);
    return this->valid(date);
  }
    
  // 验证是否有效
  ErrCode valid(Date &date) {
    // evaluate yyyy-mm-dd, not implemented
    if(date.hstart >= date.hend) return eNotValid;
    return this->shopTradeable(date);
  }
  
  // 是否在营业时间内
  ErrCode shopTradeable(Date &date) {
    int w = date.w = this->getDayByDate(date);
    
    if(0 == this->shop_tradeable_matrix_[w - 1][date.hstart - 1] or \
       0 == this->shop_tradeable_matrix_[w - 1][date.hend - 2]) return eNotValid;
    return eOK;
  }
  
  // 根据时间计算星期几
  int getDayByDate(const Date &date) {
    return this->getDayByDate(date.y, date.m, date.d);
  }
  
  // 根据时间计算星期几
  int getDayByDate(int y, int m, int d) {
    if(m == 1 || m == 2) {m += 12; y--;}
    int w = 1 + (d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400 ) % 7;
    return w;
  }
  
  // 处理记录
  ErrCode go(const ShortRecord &short_record) {
    auto &record = this->short_record_map_[short_record];
    // fprintf(stderr, "[DEBUG], start %s > short_record: %s, cop: %s, lop: %s\n", __func__, \
            short_record.c_str(), record.cop.c_str(), record.lop.c_str());
    if(record.cop == "cancel") {
      return this->cancel(short_record);
    }
    else if(record.cop == "book") {
      return this->book(short_record);
    }
    return eBadRequest;
  }
  
  // 获取折扣信息, 此处未实现细节, 默认不打折
  BookPrice fetchDiscount(const Record &record) {
    
    return 1.f;
  }
  
  // 计算预订价格
  BookPrice calcBookPrice(const Record &record) {
    BookPrice price = 0.f;
    for(int i = record.date.hstart - 1; i < record.date.hend - 1; ++i) {
      price += (this->shop_tradeable_matrix_[record.date.w][i] * this->fetchDiscount(record));
    }
    return price;
  }
  
  // 是否为同一天同一地点
  bool isTheSameDayAndPlace(const ShortRecord &sr1, const ShortRecord &sr2) {
    return (sr1.substr(0, 10) == sr2.substr(0, 10) and sr1[17] == sr2[17]);
  }
  
  // 时间是否有重叠
  bool hasIntersection(const ShortRecord &sr1, const ShortRecord &sr2) {    
    auto &r1 = this->short_record_map_[sr1];
    auto &r2 = this->short_record_map_[sr2];
    if(sr1 == sr2) {
      if(r1.lop == "book") return true;
      return false;
    }
    int s1 = r1.date.hstart, e1 = r1.date.hend, s2 = r2.date.hstart, e2 = r2.date.hend;
    // fprintf(stderr, "[%2d~%2d] [%2d~%2d]\n", s1, e1, s2, e2);
    if((s1 >= s2 and s1 < e2) or (e1 > s2 and e1 <= e2) or (s2 >= s1 and s2 < e1) or (e2 > s1 and e2 <= e1)) if(r1.lop == "book") return true;
    return false;
  }
  
  // 是否被预定
  bool isBooked(const ShortRecord &short_record) {
    bool start = false;
    for(auto &sr: this->short_record_map_) {
      // fprintf(stderr, "[DEBUG], %s > short_record_map: %s\n", __func__, sr.first.c_str());
      if(this->isTheSameDayAndPlace(sr.first, short_record)) {start = true;} else {if(start) break; else continue;}
      if(this->hasIntersection(sr.first, short_record)) return true;
    }
    return false;
  }
  
  // 预定
  ErrCode book(const ShortRecord &short_record) {
    // fprintf(stderr, "[DEBUG] > booking...\n");
    if(this->isBooked(short_record)) return eBooked;
    auto &record = this->short_record_map_[short_record];
    record.lop = record.cop; record.cop = "none";
    record.bp = this->calcBookPrice(record);
    // fprintf(stderr, "[DEBUG], after %s > short_record: %s, cop: %s, lop: %s\n", __func__,  \
            short_record.c_str(), record.cop.c_str(), record.lop.c_str());
    return eOK;
  }
  
  // 取消
  ErrCode cancel(const ShortRecord &short_record) {
    // fprintf(stderr, "[DEBUG] > canceling...\n");
    int found = this->short_record_map_.count(short_record);
    if(0 == found) return eNotFound;
    auto &record = this->short_record_map_[short_record];
    if(record.lop == "cancel") return eCanceled;
    record.lop = record.cop; record.cop = "none";
    record.cp = this->calcBookPrice(record) * (record.date.w >= 6? this->weekday_cancel_percent_: this->workday_cancel_percent_);
    // fprintf(stderr, "[DEBUG], after %s > short_record: %s, cop: %s, lop: %s\n", __func__, \
            short_record.c_str(), record.cop.c_str(), record.lop.c_str());
    return eOK;
  }
  
  // 输出
  const std::string getOutput(void) {
    fprintf(stderr, "/************************* OUTPUT *************************/\n");
    int i = 0;
    fprintf(stderr, "> 收入汇总\n> ---");
    for(auto &psr: this->place_short_records_) {
      if(i++ != 0) {
        fprintf(stderr, ">");
      }
      fprintf(stderr, "\n> 场地:%s\n", psr.first.c_str());
      ShortRecordList* srl = nullptr;
      if(nullptr != psr.second) srl = psr.second->head;
      while(nullptr != srl) {
        auto &r = this->short_record_map_[srl->short_record];
        this->print(r, false);
        srl = srl->next;
      }
      // for(auto &psri: psr.second) {
        // auto &r = this->short_record_map_[psri];
        // this->print(r, false);
      // }
      fprintf(stderr, "> 小计: %.0f元\n", this->place_price_sum_[psr.first]);
    }
    fprintf(stderr, "> ---\n> 总计: %.0f元\n", this->sum_);
    return this->output_;
  }
  
  // 打印记录
  void print(const Record &record, bool full = true) {
    if(full) {
      fprintf(stderr, "[DEBUG] > %s %04d-%02d-%02d %02d:00~%02d:00 %s [%s]\n", \
              record.user.c_str(), record.date.y, record.date.m, record.date.d, \
              record.date.hstart, record.date.hend, record.place.c_str(), record.cop.c_str());
    }
    else {
      fprintf(stderr, "> %04d-%02d-%02d %02d:00~%02d:00 %s%.0f元\n", \
              record.date.y, record.date.m, record.date.d, \
              record.date.hstart, record.date.hend, \
              (record.lop == "cancel"? "违约金 ": ""), (record.lop == "cancel"? record.cp: record.bp));
      if(record.lop == "cancel") {
        this->sum_ += record.cp;
        this->place_price_sum_[record.place] += record.cp;
        
      }
      else {
        this->sum_ += record.bp;
        this->place_price_sum_[record.place] += record.bp;
      }
    }
  }
  
protected:
  std::vector<std::string> places_;
  std::map<Place, ShortRecordList*> place_short_records_;
  ShortRecordMap short_record_map_;
  std::map<Place, BookPrice> place_price_sum_;
  std::string output_;
  std::vector<std::vector<float> > shop_tradeable_matrix_;
  BookPrice sum_;
  CancelPrice workday_cancel_percent_;
  CancelPrice weekday_cancel_percent_;
};
/************* Booker **************/

/************* TEST **************/
TEST(BookerTest, test1) {
  std::vector<std::string> input_testinstance = {
    "abcdefghijklmnopqrst1234567890", 
    "U001 2016-06-02 22:00~22:00 A", 
    "U002 2017-08-01 19:00~22:00 A", 
    "U003 2017-08-02 13:00~17:00 B", 
    "U004 2017-08-03 15:00~16:00 C", 
    "U005 2017-08-05 09:00~11:00 D", 
  };
  
  std::vector<std::string> input_out_testinstance = {
    "Error: the booking is invalid!", 
    "Error: the booking is invalid!", 
    "Success: the booking is accepted!", 
    "Success: the booking is accepted!", 
    "Success: the booking is accepted!", 
    "Success: the booking is accepted!", 
  };
  
  const std::string output = "\
> 收入汇总\n\
> ---\n\
> 场地:A\n\
> 2017-08-01 19:00~22:00 200元\n\
> 小计: 200元\n\
>\n\
> 场地:B\n\
> 2017-08-02 13:00~17:00 200元\n\
> 小计: 200元\n\
>\n\
> 场地:C\n\
> 2017-08-03 15:00~16:00 50元\n\
> 小计: 50元\n\
>\n\
> 场地:D\n\
> 2017-08-05 09:00~11:00 80元\n\
> 小计: 80元\n\
> ---\n\
> 总计: 530元\n\
";
  
  auto p = new Booker;
  ASSERT_TRUE(p != nullptr);
  for(int i = 0; i < input_testinstance.size(); ++i) {
    EXPECT_EQ(p->getInput(input_testinstance[i]), input_out_testinstance[i]);
  }
  fprintf(stderr, "%s", output.c_str());
  p->getOutput();
  delete p;
}

TEST(BookerTest, test2) {
  std::vector<std::string> input_testinstance = {
    "U002 2017-08-01 19:00~22:00 A", 
    "U003 2017-08-01 18:00~20:00 A", 
    "U002 2017-08-01 19:00~22:00 A C", 
    "U002 2017-08-01 19:00~22:00 A C", 
    "U003 2017-08-01 18:00~20:00 A", 
    "U003 2017-08-02 13:00~17:00 B", 
  };
  
  std::vector<std::string> input_out_testinstance = {
    "Success: the booking is accepted!", 
    "Error: the booking conflicts with existing bookings!", 
    "Success: the booking is accepted!", 
    "Error: the booking being cancelled does not exist!", 
    "Success: the booking is accepted!", 
    "Success: the booking is accepted!", 
  };
  
  const std::string output = "\
> 收入汇总\n\
> ---\n\
> 场地:A\n\
> 2017-08-01 18:00~20:00 160元\n\
> 2017-08-01 19:00~22:00 违约金 100元\n\
> 小计:260元\n\
>\n\
> 场地:B\n\
> 2017-08-02 13:00~17:00 200元\n\
> 小计:200元\n\
>\n\
> 场地:C\n\
> 小计:0元\n\
>\n\
> 场地:D\n\
> 小计:0元\n\
> ---\n\
> 总计:460元\n\
";
  
  auto p = new Booker;
  ASSERT_TRUE(p != nullptr);
  for(int i = 0; i < input_testinstance.size(); ++i) {
    EXPECT_EQ(p->getInput(input_testinstance[i]), input_out_testinstance[i]);
  }
  fprintf(stderr, "%s", output.c_str());
  p->getOutput();
  delete p;
}

TEST(BookerTest, test3) {
  std::vector<std::string> input_testinstance = {
    "U002 2017-08-01 19:00~22:00 A", 
    "U003 2017-08-01 18:00~20:00 A", 
    "U002 2017-08-01 19:00~22:00 A C", 
    "U002 2017-08-01 19:00~22:00 A C", 
    "U003 2017-08-01 18:00~20:00 A", 
    "U003 2017-08-02 13:00~17:00 B", 
    "U003 2017-08-02 13:00~17:00 B D", 
    "U003 2017-08-02 13:00~17:00 B", 
  };
  
  std::vector<std::string> input_out_testinstance = {
    "Success: the booking is accepted!", 
    "Error: the booking conflicts with existing bookings!", 
    "Success: the booking is accepted!", 
    "Error: the booking being cancelled does not exist!", 
    "Success: the booking is accepted!", 
    "Success: the booking is accepted!", 
    "Error: the booking is invalid!", 
    "Error: the booking conflicts with existing bookings!", 
  };
  
  const std::string output = "\
> 收入汇总\n\
> ---\n\
> 场地:A\n\
> 2017-08-01 18:00~20:00 160元\n\
> 2017-08-01 19:00~22:00 违约金 100元\n\
> 小计:260元\n\
>\n\
> 场地:B\n\
> 2017-08-02 13:00~17:00 200元\n\
> 小计:200元\n\
>\n\
> 场地:C\n\
> 小计:0元\n\
>\n\
> 场地:D\n\
> 小计:0元\n\
> ---\n\
> 总计:460元\n\
";
  
  auto p = new Booker;
  ASSERT_TRUE(p != nullptr);
  for(int i = 0; i < input_testinstance.size(); ++i) {
    EXPECT_EQ(p->getInput(input_testinstance[i]), input_out_testinstance[i]);
  }
  fprintf(stderr, "%s", output.c_str());
  p->getOutput();
  delete p;
}
/************* TEST **************/


int main(int argc, char **argv) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();;
}

编辑于 2018-08-29 14:24:10 回复(0)
faf
发表于 2018-07-25 08:54:02 回复(0)
#!/Users/sunxuanzhi/anaconda3/bin/python3
# -*- coding:utf-8 -*-
#author:xuanzhi
import datetime
import time
from pprint import pprint
import collections

class Stadium_Booking():
    def __init__(self):
        self.info = {'A':{},'B':{},'C':{},'D':{}}
        self._BOOKING_TM = ['09'] + [str(i) for i in range(10,23)]
        self._dates = {'A':[],'B':[],'C':[],'D':[]}
        self._fees = {'A':{},'B':{},'C':{},'D':{}}

    def _func_1(self):
        _BOOK_TM = {}
        for i in range(9,22):
            _BOOK_TM.update({i:''})
        return _BOOK_TM

    def _earning(self):
        _total = 0
        print('> 收入汇总\n> ---')
        for _bk_plc,_ff in self._ordered_dict().items():
            _temp_total = 0
            print('> 场地: ',_bk_plc)
            #print(_ff)
            for item in _ff:
                if item[-1][0] != 0:
                    _temp_total += item[-1][0]
                    print('> ',item[0],' ',str(item[-1][0]),'元')
                else:
                    _temp_total += item[-1][-1]
                    print('> ',item[0],' 违约金 ',str(item[-1][-1]),'元')
            _total += _temp_total
            print('> 小计: ',str(_temp_total),'元')
            print('>')
        print('> ---\n> 总计:  ',str(_total),'元')

    def _ordered_dict(self):
        _raw_fees = {}
        _ordered_list = []
        self._ordered_fees = {}
        for i,j in self._fees.items():
            _raw_fees = {}
            _raw_fees_tm = {}
            _min_ts = 0
            _single_list = []
            for m,n in j.items():
                _booking_dt, _booking_tm = m.split(' ')[0], m.split(' ')[1]
                _start_tm = _booking_tm.split('~')[0].split(':')[0]
                _dtime = datetime.datetime.strptime(_booking_dt + _start_tm.split(':')[0],'%Y-%m-%d%H')
                _unix_tm = int(time.mktime(_dtime.timetuple()))
                _raw_fees_tm.update({_unix_tm:m})
                _raw_fees.update({_unix_tm:n})
            #print(_raw_fees_tm)
            for key in sorted(_raw_fees.keys()):
                    _single_list.append([_raw_fees_tm[key],_raw_fees[key]])                
            self._ordered_fees.update({i:_single_list})
        return self._ordered_fees





    def _check_input(self,_input_str):
        if _input_str == '收入汇总':
            self._earning()
            return None
        _input_list = _input_str.strip().split(' ')
        #print(_input_list)
        try:
            if _input_list[3] not in self.info.keys():
                return []
            if not self._check_time(_input_list[1]+' '+_input_list[2])[0]:
                #print(_input_list[1]+' '+_input_list[2])
                return []
            return _input_list
        except:
            return []


    def _get_input(self,_input):
        _input_list = self._check_input(_input)
        #print(_input_list)
        if _input_list == None:
            return None
        if len(_input_list) == 4:
            _user_name, _booking_time, _booking_place  = _input_list[0], _input_list[1]+' '+_input_list[2], _input_list[3]
            #print(_user_name, _booking_time, _booking_place)
            _status = self._check_status(_booking_place, _booking_time, _user_name)
            if _status == 'free':
                print('> Success: the booking is accepted!')
            elif _status == 'bad_input':
                print('> Error: the booking is invalid!')
            elif _status == 'has_been_booked':
                print('> Error: the booking conflicts with existing bookings!')
            #print('--------------------------')
        elif len(_input_list) == 5 and _input_list[4] == 'C':
            _user_name, _booking_time, _booking_place, _cancel  = _input_list[0], _input_list[1]+' '+_input_list[2], _input_list[3], _input_list[4]
            #print(_booking_place, _booking_time, _user_name, _cancel)
            _status = self._check_status(_booking_place, _booking_time, _user_name, _cancel)
            if _status == 'can_be_canceled':
                print('> Success: the booking is accepted!')
            elif _status == 'bad_input':
                print('> Error: the booking is invalid!')
            elif _status == 'free':
                print('> Error: the booking being cancelled does not exist!')
            #print('--------------------------')
        else:
            print('> Error: the booking is invalid!')
            #print('--------------------------')


    def _check_status(self,_booking_place, _booking_time, _user_name, _cancel=None ):
        #print(_user_name, _booking_time, _booking_place,_cancel)
        if _booking_place in self.info.keys() and self._check_time(_booking_time)[0]:
            _booking_hours = [i for i in range(int(_booking_time.split(' ')[1].split('~')[0].split(':')[0]),int(_booking_time.split(' ')[1].split('~')[1].split(':')[0]))]
            #print(_booking_hours)
            if _cancel == None:
                _temp_ts = int(time.time())
                #print(self._dates)
                if _booking_time.split(' ')[0] not in self._dates[_booking_place]:
                    self._dates[_booking_place].append(_booking_time.split(' ')[0])
                    self.info[_booking_place][_booking_time.split(' ')[0]] = self._func_1()
                    for hour in _booking_hours:
                        if self.info[_booking_place][_booking_time.split(' ')[0]][hour] == '':
                            self.info[_booking_place][_booking_time.split(' ')[0]][hour] = [_user_name,_temp_ts]
                    #pprint(self.info)
                    _booking_once_fee = self._week_fees(self._check_time(_booking_time)[1],_booking_hours)
                    self._fees[_booking_place][_booking_time] = [_booking_once_fee,0]
                    return 'free'
                else:
                    for hour in _booking_hours:
                        if self.info[_booking_place][_booking_time.split(' ')[0]][hour] != '':
                            return 'has_been_booked'
                    for hour in _booking_hours: 
                        self.info[_booking_place][_booking_time.split(' ')[0]][hour] = [_user_name,_temp_ts]
                    _booking_once_fee = self._week_fees(self._check_time(_booking_time)[1],_booking_hours)
                    self._fees[_booking_place][_booking_time] = [_booking_once_fee,0]
                    return 'free'
            else:
                if _booking_time.split(' ')[0] not in self._dates[_booking_place]:
                    return 'free'
                for hour in _booking_hours:
                    if self.info[_booking_place][_booking_time.split(' ')[0]][hour][0] != _user_name:
                        return 'free'
                _ts = self.info[_booking_place][_booking_time.split(' ')[0]][hour][1]
                for hour in _booking_hours:
                    if self.info[_booking_place][_booking_time.split(' ')[0]][hour][1] != _ts:
                        return 'free'
                    else:
                        self.info[_booking_place][_booking_time.split(' ')[0]][hour] = ''
                if self.info[_booking_place][_booking_time.split(' ')[0]] == self._func_1():
                    self._dates[_booking_place].remove(_booking_time.split(' ')[0])
                _original_fee = self._fees[_booking_place][_booking_time][0]
                if self._check_time(_booking_time)[1] in [k for k in range(5)]:
                    self._fees[_booking_place][_booking_time] = [0,int(_original_fee*0.5)]
                else:
                    self._fees[_booking_place][_booking_time] = [0,int(_original_fee*0.25)]
                return 'can_be_canceled'
        else:
            return 'bad_input'

    def _week_fees(self,_week_day,_booking_hours):
        _fee = 0
        #print(_booking_hours)
        if _week_day in [k for k in range(5)]:
            for i in _booking_hours:
                i = str(i)
                if i == '9':
                    i = '09'
                if i in self._BOOKING_TM[:3]:
                    _fee += 30
                elif i in self._BOOKING_TM[3:9]:
                    _fee += 50
                elif i in self._BOOKING_TM[9:11]:
                    _fee += 80
                else:
                    _fee += 60
        else:
            for i in _booking_hours:
                i = str(i)
                if i == '9':
                    i = '09'
                if i in self._BOOKING_TM[:3]:
                    _fee += 40
                elif i in self._BOOKING_TM[3:9]:
                    _fee += 50
                else:
                    _fee += 60
        return _fee





    #检查预定时间是否合法
    def _check_time(self, _booking_time):
        _booking_dt, _booking_tm = _booking_time.split(' ')[0], _booking_time.split(' ')[1]
        #print(_booking_dt, _booking_tm)
        try:
            _booking_datetime = datetime.datetime.strptime(_booking_dt,'%Y-%m-%d')
            week_day = _booking_datetime.weekday()
        except:
            return False
        try:
            #print(_booking_datetime,type(_booking_datetime))
            _start_tm, _end_tm = _booking_tm.split('~')[0], _booking_tm.split('~')[1]
            #print(_start_tm, _end_tm)

            if _start_tm[-2:] != '00' or _end_tm[-2:] != '00':
                return False    
            elif (_start_tm.split(':')[0] not in self._BOOKING_TM) or (_end_tm.split(':')[0] not in self._BOOKING_TM) or (int(_start_tm.split(':')[0]) >= int(_end_tm.split(':')[0])) :
                return False
            else:
                return True, week_day
        except:
            return False





if __name__ == '__main__':
    client = Stadium_Booking()    
    #test_1
    #client._get_input('abcdefghijklmnopqrst1234567890')
    #client._get_input('U001 2016-06-02 22:00~22:00 A')
    #client._get_input('U002 2017-08-01 19:00~22:00 A')
    #client._get_input('U003 2017-08-02 13:00~17:00 B')
    #client._get_input('U004 2017-08-03 15:00~16:00 C')
    #client._get_input('U005 2017-08-05 09:00~11:00 D')
    #test_2
    #client._get_input('U002 2017-08-01 19:00~22:00 A')
    #client._get_input('U003 2017-08-01 18:00~20:00 A')
    #client._get_input('U002 2017-08-01 19:00~22:00 A C')
    #client._get_input('U002 2017-08-01 19:00~22:00 A C')
    #client._get_input('U003 2017-08-01 18:00~20:00 A')
    #client._get_input('U003 2017-08-02 13:00~17:00 B')
    #pprint(client.info)
    #print(client._dates)
    #print(client._fees)
    #print(client._ordered_dict())
    #client._earning()
    while True:
        _keyboard_input = input()
        client._get_input(_keyboard_input)









发表于 2018-07-24 16:48:56 回复(0)
链接:https://www.nowcoder.com/questionTerminal/4c3d325a70fd4fb4909e2fe1c42fba71?orderByHotValue=0&mutiTagIds=570&page=1&onlyReference=false 来源:牛客网
publicclassCustomer {
 
String userID;
 
intyear;
 
intmonth;
 
intday;
 
intstartClock;
 
intendClock;
 
String place;
 
publicCustomer(String id,intyear,intmonth,intday,intstartClock,intendClock, String placa) {
 
this.userID = id;
 
this.year = year;
 
this.month = month;
 
this.day = day;
 
this.startClock = startClock;
 
this.endClock = endClock;
 
this.place = placa;
 
}
 
publicbooleanisIDEuqal(Customer c) {
 
if(this.userID.equals(c.userID))
 
returntrue;
 
returnfalse;
 
}
 
publicbooleanisDateEqual(Customer c) {
 
if(this.year == c.year &&this.month == c.month &&this.day == c.day)
 
returntrue;
 
returnfalse;
 
}
 
publicbooleanisPlaceEqual(Customer c) {
 
if(this.place.equals(c.place))
 
returntrue;
 
returnfalse;
 
}
 
publicbooleanisEqual(Customer c) {
 
if(this.userID.equals(c.userID) &&this.year == c.year &&this.month == c.month &&this.day == c.day &&this.startClock == c.startClock &&this.endClock == c.endClock)
 
returntrue;
 
returnfalse;
 
}
 
publicbooleanisTimeConflict(Customer c) {
 
if(isDateEqual(c) && 
 
((this.startClock < c.startClock &&this.endClock < c.endClock &&this.endClock > c.startClock) 
 
||(this.startClock > c.startClock &&this.startClock < c.endClock &&this.endClock > c.startClock &&this.endClock < c.endClock)
 
||(this.startClock > c.startClock &&this.startClock < c.endClock &&this.endClock > c.endClock)
 
||(c.startClock <this.startClock && c.endClock <this.endClock && c.endClock >this.startClock)
 
||(c.startClock >this.startClock && c.startClock <this.endClock && c.endClock >this.startClock && c.endClock <this.endClock)
 
||(c.startClock >this.startClock && c.startClock <this.endClock && c.endClock >this.endClock))
 
&& isPlaceEqual(c))
 
returntrue;
 
returnfalse;
 
}
 
}
 
     
 
     
 
     
 
importjava.io.BufferedReader;
 
importjava.io.File;
 
importjava.io.FileInputStream;
 
importjava.io.InputStreamReader;
 
importjava.util.List;
 
importjava.util.regex.Matcher;
 
importjava.util.regex.Pattern;
 
importjava.text.ParseException;
 
importjava.text.SimpleDateFormat;
 
importjava.util.ArrayList;
 
importjava.util.Date;
 
importjava.util.LinkedList;
 
importjava.util.Scanner;
 
publicclassMain {
 
staticString[] str =newString[21];
 
/*
 
str[1]: user ID
 
str[4]: start year
 
str[6]: start month
 
str[8]: start day
 
str[10]: start clock
 
str[14]: end clock
 
str[18]: Accept
 
str[20]: Concel
 
*/
 
staticintminStartClock =9;
 
staticintmaxEndClock =22;
 
staticList<Customer>   bookList =newLinkedList<>();
 
staticList<Customer> concelList =newArrayList<>();
 
publicstaticvoidmain(String[] args) {
 
Scanner sc =newScanner(System.in);
 
sc.useDelimiter("\n");
 
String line ="";
 
while(line.length() !=1&& line !=" ") {
 
line = sc.nextLine();
 
// System.out.println(line);
 
if(line.length() !=1&& line !=" ")
 
mainProcess(line);
 
}
 
printResult();
 
// String [] line = new String[6];
 
// line[0] = "U002 2017-08-01 19:00~22:00 A";
 
// line[1] = "U003 2017-08-01 18:00~20:00 A";
 
// line[2] = "U002 2017-08-01 19:00~22:00 A C";
 
// line[3] = "U002 2017-08-01 19:00~22:00 A C";
 
// line[4] = "U003 2017-08-01 18:00~20:00 A";
 
// line[5] = "U003 2017-08-02 13:00~17:00 B";
 
// for (String l:line) {
 
// mainProcess(l);;
 
// }
 
// printResult();
 
}
 
publicstaticvoidmainProcess(String line) {
 
String userID;
 
intyear;
 
intmonth;
 
intday;
 
intstartClock;
 
intendClock;
 
String place;
 
String bookPattern ="(U)(\\d{3})(\\s)(\\d{4})(-)(\\d{2})(-)(\\d{2})(\\s)(\\d{2})(:)(00)(~)(\\d{2})(:)(00)(\\s)([A-D])";
 
String concelPattern ="(U)(\\d{3})(\\s)(\\d{4})(-)(\\d{2})(-)(\\d{2})(\\s)(\\d{2})(:)(00)(~)(\\d{2})(:)(00)(\\s)([A-D])(\\s)([C])";
 
booleanisBook = Pattern.matches(bookPattern, line);
 
booleanisConcel = Pattern.matches(concelPattern, line);
 
// System.out.println(line);
 
if(isBook) {
 
// System.out.println(Pattern.matches(bookPattern, line));
 
Pattern p = Pattern.compile(bookPattern);
 
Matcher m = p.matcher(line);
 
// System.out.println(m.groupCount());
 
m.find();
 
for(intj =0; j < m.groupCount()+1; j++) {
 
str[j] = m.group(j);
 
// System.out.println(str[j]);
 
}
 
// System.out.println(str[20]);
 
userID = str[2];
 
year = Integer.valueOf(str[4]);
 
month = Integer.valueOf(str[6]);
 
day = Integer.valueOf(str[8]);
 
startClock = Integer.valueOf(str[10]);
 
endClock = Integer.valueOf(str[14]);
 
place = str[18];
 
// bookMessage = year + month + day + 
 
// 如果与预定表达式一样的话,那么看预定的时间是否相等,预定的开始时间是否小于最小开始时间,结束时间是否大于最大结束时间,如果是的话,打印预定不正确错误。
 
if(Integer.valueOf(startClock) == Integer.valueOf(endClock) 
 
|| Integer.valueOf(startClock) < minStartClock 
 
|| Integer.valueOf(endClock) > maxEndClock)
 
printInvalidBookError();
 
else{
 
Customer cus =newCustomer(userID, year, month, day, startClock, endClock, place);
 
book(cus);
 
}
 
}elseif(isConcel) {
 
Pattern p = Pattern.compile(concelPattern);
 
Matcher m = p.matcher(line);
 
// System.out.println(m.groupCount());
 
m.find();
 
for(intj =0; j < m.groupCount()+1; j++) {
 
str[j] = m.group(j);
 
// System.out.println(str[j]);
 
}
 
// System.out.println(str[20]);
 
userID = str[2];
 
year = Integer.valueOf(str[4]);
 
month = Integer.valueOf(str[6]);
 
day = Integer.valueOf(str[8]);
 
startClock = Integer.valueOf(str[10]);
 
endClock = Integer.valueOf(str[14]);
 
place = str[18];
 
Customer cus =newCustomer(userID, year, month, day, startClock, endClock, place);
 
concelBook(cus); 
 
 
else{
 
printInvalidBookError();
 
 
}
 
publicstaticvoidbook(Customer cus){
 
for(Customer c:bookList) {
 
if(c.isTimeConflict(cus)) {
 
printConflictError();
 
return;
 
}
 
}
 
bookList.add(cus);
 
printBookSuccess();
 
}
 
publicstaticvoidconcelBook(Customer cus){
 
booleanrem =false;
 
for(Customer c:bookList) {
 
if(cus.isEqual(c)) {
 
bookList.remove(c);
 
concelList.add(cus);
 
printBookSuccess();
 
rem =true;
 
}
 
}
 
if(!rem)
 
printConcelError();
 
}
 
publicstaticvoidprintResult() {
 
String [] placeIncome =newString[4];
 
int[] placePrice =newint[4];
 
int bookIncome;
 
intconcelIncome;
 
for(intj ='A', k =0; j <='D'; j ++, k++) {
 
placeIncome[k] ="场地"+ String.valueOf((char)(j)) +":\n";
 
}
 
System.out.println("\n"+"收入汇总\n"+"---");
 
for(Customer c:bookList) {
 
bookIncome = calPrice(c);
 
for(intj ='A', k =0; j <='D'; j ++, k++) {
 
if((String.valueOf((char)(j))).equals(c.place)) {
 
placePrice[k] += bookIncome;
 
placeIncome[k] += (c.year +"-"+ (c.month <10? ("0"+ c.month):c.month) +"-"+ (c.day <10? ("0"+ c.day):c.day) +" "
 
+ (c.startClock <10? ("0"+ c.startClock):c.startClock)+":"+"00"+"~"
 
+(c.endClock<10? ("0"+ c.endClock):c.endClock)+":"+"00"
 
+" "+ bookIncome +"元"+"\n");
 
}
 
}
 
// System.out.println(bookIncome);
 
}
 
for(Customer c:concelList) {
 
concelIncome = calConcel(c); 
 
for(intj ='A', k =0; j <='D'; j ++, k++) {
 
if((String.valueOf((char)(j))).equals(c.place)) {
 
placePrice[k] += concelIncome;
 
placeIncome[k] += (c.year +"-"+ (c.month <10? ("0"+ c.month):c.month) +"-"+ (c.day <10? ("0"+ c.day):c.day) +" "
 
+ (c.startClock <10? ("0"+ c.startClock):c.startClock)+":"+"00"+"~"
 
+(c.endClock<10? ("0"+ c.endClock):c.endClock)+":"+"00"
 
+" 违约金"+" "+ concelIncome +"元\n");
 
}
 
}
 
}
 
inti =0;
 
intsumPrice =0;
 
for(String p:placeIncome) {
 
sumPrice += placePrice[i];
 
System.out.print(p);
 
System.out.println("小计:"+ placePrice[i++] +"元");
 
System.out.println();
 
}
 
System.out.println("---\n"+"总计:"+ sumPrice +"元");
 
}
 
publicstaticintcalConcel(Customer c) {
 
return(int) (calPrice(c) * (getWeek(c) <=5?0.5:0.25));
 
}
 
publicstaticintgetWeek(Customer c) {
 
String[] weeks = {"星期一","星期二","星期三","星期四","星期五","星期六","星期日"}; 
 
String strDate = c.year +"-"+ c.month +"-"+ c.day;
 
SimpleDateFormat f =newSimpleDateFormat("yyyy-MM-dd");
 
Date date =null;
 
try{ 
 
date = f.parse(strDate);// 将字符串转换为日期 
 
}catch(ParseException e) { 
 
System.out.println("输入的日期格式不合理!"); 
 
}
 
SimpleDateFormat sdf =newSimpleDateFormat("EEEE"); 
 
String week = sdf.format(date); 
 
for(inti =0; i < weeks.length; i++) {
 
if(week.equals(weeks[i]))
 
return++i;
 
}
 
return0;
 
}
 
publicstaticintcalPrice(Customer c) {
 
int[] workDayPrice = {30,50,80,60};
 
int[] weekDayPrice = {40,50,60};
 
intweek = getWeek(c);
 
intprice =0;
 
if(week <=5) {// 周一到周五的价格计算
 
if(c.startClock >=9&& c.startClock <=12) {
 
if(c.endClock >=9&& c.endClock <=12) {
 
price = (c.endClock - c.startClock) * workDayPrice[0];
 
}elseif(c.endClock >12&& c.endClock <=18) {
 
price = (12- c.startClock) * workDayPrice[0] + (c.endClock -12) * workDayPrice[1];
 
}elseif(c.endClock >18&& c.endClock <=20) {
 
price = (12- c.startClock) * workDayPrice[0] + (18-12) * workDayPrice[1] 
 
+ (c.endClock -18) * workDayPrice[2];
 
}elseif(c.endClock >20&& c.endClock <=22) {
 
price = (12- c.startClock) * workDayPrice[0] + (18-12) * workDayPrice[1] 
 
+ (20-18) * workDayPrice[2] + (c.endClock -20) * workDayPrice[3];
 
}
 
 
elseif (c.startClock >12&& c.startClock <=18){
 
if(c.endClock >=12&& c.endClock <=18) 
 
price = (c.endClock - c.startClock) * workDayPrice[1];
 
elseif(c.endClock >18&& c.endClock <=20) 
 
price = (18- c.startClock) * workDayPrice[1] 
 
+ (c.endClock -18) * workDayPrice[2];
 
elseif(c.endClock >20&& c.endClock <=22) 
 
price = (18- c.startClock) * workDayPrice[1] + (20-18) * workDayPrice[2]
 
+ (c.endClock -20) * workDayPrice[3];
 
}
 
else if(c.startClock >18&& c.startClock <=20) {
 
if(c.endClock >=18&& c.endClock <=20)
 
price = (c.endClock - c.startClock) * workDayPrice[2];
 
elseif(c.endClock >20&& c.endClock <=22) {
 
price = (20- c.startClock) * workDayPrice[2] + (c.endClock -20) * workDayPrice[3];
 
}
 
}
 
elseif(c.startClock >20&& c.startClock <=22) {
 
price = (c.endClock - c.startClock) * workDayPrice[3];
 
}
 
 
else{
 
if(c.startClock >=9&& c.endClock <=12) {
 
if(c.endClock >9&& c.endClock <=12) {
 
price = (c.endClock - c.startClock) * weekDayPrice[0];
 
}elseif(c.endClock >12&& c.endClock <=18) {
 
price = (12- c.startClock) * weekDayPrice[0] + (c.endClock -12) * weekDayPrice[1];
 
}elseif(c.endClock >18&& c.endClock <=22) {
 
price = (12- c.startClock) * weekDayPrice[0] + (18-12) * weekDayPrice[1]
 
+ (c.endClock -18) * weekDayPrice[2];
 
}
 
}elseif(c.startClock >12&& c.startClock <=18) {
 
if(c.endClock >12&& c.endClock <=18)
 
price = (c.endClock - c.startClock) * weekDayPrice[1];
 
elseif(c.endClock >18&& c.endClock <=22) 
 
price = (18- c.startClock) * weekDayPrice[1] + (c.endClock -18) * weekDayPrice[2];
 
}elseif(c.startClock >18&& c.startClock <=22) {
 
price = (c.endClock - c.startClock) * weekDayPrice[2];
 
}
 
}
 
returnprice;
 
}
 
publicstaticvoidprintInvalidBookError() {
 
System.out.println("Error: the booking is invalid!");
 
}
 
publicstaticvoidprintConflictError(){
 
System.out.println("Error: the booking conflicts with existing bookings!");
 
}
 
publicstaticvoidprintConcelError() {
 
System.out.println("Error: the booking being cancelled does not exist!");
 
}
 
publicstaticvoidprintBookSuccess(){
 
System.out.println("Success: the booking is accepted!");
 
}
 
}

发表于 2018-06-23 17:03:42 回复(0)
结合GUI可用 python 开发
发表于 2018-06-16 13:53:39 回复(0)
此次v
发表于 2018-06-14 17:18:01 回复(0)
好难
发表于 2018-05-26 12:27:25 回复(0)
N个孩子站成一排,给每个人设定一个权重(已知)。按照如下的规则分配糖果: (1)每个孩子至少分得一颗糖果 (2)权重较高的孩子,会比他的邻居获得更多的糖果。 问:总共最少需要多少颗糖果?请分析算法思路,以及算法的时间,空间复杂度是多少。
发表于 2018-04-27 19:42:38 回复(0)
Good
发表于 2018-04-08 12:19:05 回复(0)
what
发表于 2018-03-30 20:08:03 回复(0)