1013-1016

来源:互联网 发布:火车头数据采集器 编辑:程序博客网 时间:2024/06/05 14:27

1013. Battle Over Cities (25)

It is vitally important to have all the cities connected by highways in a war. If a city is occupied by the enemy, all the highways from/toward that city are closed. We must know immediately if we need to repair any other highways to keep the rest of the cities connected. Given the map of cities which have all the remaining highways marked, you are supposed to tell the number of highways need to be repaired, quickly.

For example, if we have 3 cities and 2 highways connecting city1-city2 and city1-city3. Then if city1 is occupied by the enemy, we must have 1 highway repaired, that is the highway city2-city3.

Input

Each input file contains one test case. Each case starts with a line containing 3 numbers N (<1000), M and K, which are the total number of cities, the number of remaining highways, and the number of cities to be checked, respectively. Then M lines follow, each describes a highway by 2 integers, which are the numbers of the cities the highway connects. The cities are numbered from 1 to N. Finally there is a line containing K numbers, which represent the cities we concern.

Output

For each of the K cities, output in a line the number of highways need to be repaired if that city is lost.

Sample Input
3 2 3
1 2
1 3
1 2 3
Sample Output
1
0
0

代码:

######## dfs ##################@author cxlualine1 = input().split()num_city = int(line1[0])num_road = int(line1[1])num_check = int(line1[2])graph = [([0] * num_city) for i in range(num_city)]road = []for i in range(num_road):    road.append(input().split())    v = int(road[i][0]) - 1    w = int(road[i][1]) - 1    graph[v][w] = graph[w][v] = 1# marked = [False] * num_city# num = 0# lost = 0def dfs(node):    global marked, graph, num_city, num, lost    marked[node] = True    for i in range(num_city):        if (graph[node][i] == 1) and (not marked[i]) and (i != lost):            dfs(i)    returndef checknode(lost):    global marked, graph, num_city, num    # for j in range(num_city):    #   if graph[lost][j] == 1:    #       graph[lost][j] = graph[j][lost] = -1    # marked[lost] = True    # while(False in marked):    #   dfs(marked.index(False))    #   num += 1    for i in range(num_city):        if (not marked[i]) and (i != lost):            num += 1            dfs(i)    return #num - 1#maincheck = input().split()for i in range(len(check)):    lost = int(check[i]) - 1    marked = [False] * num_city    # if i != 0:    #   for m in range(num_city):    #       # if graph[m][int(check[i-1]) - 1] == -1:    #       #   graph[m][int(check[i-1]) - 1] = graph[int(check[i-1]) - 1][m] = 1    #       marked[m] = False    num = 0    # print(checknode(lost))    checknode(lost)    print(num - 1)########## union-find #################@author cxlualine1 = input().split()num_city = int(line1[0])num_road = int(line1[1])num_check = int(line1[2])records = []pairs = [[0, 0] for i in range(num_road)]for i in range(num_road):    records.append(input().split())    pairs[i][0] = int(records[i][0]) - 1    pairs[i][1] = int(records[i][1]) - 1# count = num_city - 1# print(pairs)def find(node):    global ide    while(node != ide[node]):        ide[node] = ide[ide[node]]        node = ide[node]    return nodedef union(node1, node2):    global count, ide    p = find(node1)    q = find(node2)    if p == q:        return    if sz[p] >= sz[q]:        ide[q] = p        sz[p] += sz[q]    else:        ide[p] = q        sz[q] += sz[p]    # ide[p] = q    count -= 1    return#maincheck = input().split()# id = [i for i in range(num_city)]for i in range(num_check):    lost = int(check[i]) - 1    count = num_city - 1    ide = [j for j in range(num_city)]    sz = [1 for j in range(num_city)]    for j in range(num_road):        if pairs[j][0] != lost and pairs[j][1] != lost:            union(pairs[j][0], pairs[j][1])    print(count - 1)

tips:
1. 实际上一个求连通分量的问题,有n个连通分量,则需要建路的数量为n-1
2. 两种算法,dfs耗时较长,每check一个城市,要做多次深度搜索;union-find每check一个城市只需要做一次union-find,但最后一个case内存超限。
3. 注意给的点的序号需要-1才是程序中城市的标号。
4. 每check一个城市,不需要改变邻接矩阵的元素,只要在函数的if中加一个不为lost节点的条件即可。

1014. Waiting in Line (30)

Suppose a bank has N windows open for service. There is a yellow line in front of the windows which devides the waiting area into two parts. The rules for the customers to wait in line are:

The space inside the yellow line in front of each window is enough to contain a line with M customers. Hence when all the N lines are full, all the customers after (and including) the (NM+1)st one will have to wait in a line behind the yellow line.
Each customer will choose the shortest line to wait in when crossing the yellow line. If there are two or more lines with the same length, the customer will always choose the window with the smallest number.
Customer[i] will take T[i] minutes to have his/her transaction processed.
The first N customers are assumed to be served at 8:00am.
Now given the processing time of each customer, you are supposed to tell the exact time at which a customer has his/her business done.

For example, suppose that a bank has 2 windows and each window may have 2 custmers waiting inside the yellow line. There are 5 customers waiting with transactions taking 1, 2, 6, 4 and 3 minutes, respectively. At 08:00 in the morning, customer1 is served at window1 while customer2 is served at window2. Customer3 will wait in front of window1 and customer4 will wait in front of window2. Customer5 will wait behind the yellow line.

At 08:01, customer1 is done and customer5 enters the line in front of window1 since that line seems shorter now. Customer2 will leave at 08:02, customer4 at 08:06, customer3 at 08:07, and finally customer5 at 08:10.

Input

Each input file contains one test case. Each case starts with a line containing 4 positive integers: N (<=20, number of windows), M (<=10, the maximum capacity of each line inside the yellow line), K (<=1000, number of customers), and Q (<=1000, number of customer queries).

The next line contains K positive integers, which are the processing time of the K customers.

The last line contains Q positive integers, which represent the customers who are asking about the time they can have their transactions done. The customers are numbered from 1 to K.

Output

For each of the Q customers, print in one line the time at which his/her transaction is finished, in the format HH:MM where HH is in [08, 17] and MM is in [00, 59]. Note that since the bank is closed everyday after 17:00, for those customers who cannot be served before 17:00, you must output “Sorry” instead.

Sample Input
2 2 7 5
1 2 6 4 3 534 2
3 4 5 6 7
Sample Output
08:07
08:06
08:10
17:00
Sorry

代码:

#@author cxluaimport collectionsline1 = [int(i) for i in input().split()]n = line1[0] m = line1[1] k = line1[2] q = line1[3] process =  [int(i) for i in input().split()]process_time = collections.deque(process) qlist = [int(i) for i in input().split()]def totime(time):    hour = 8 + time // 60    minute = 0 + time % 60    return str(hour).zfill(2) + ':' + str(minute).zfill(2)window = {}for i in range(n):    window[i] = collections.deque()res = [] ## result listinnum = 0outnum = k - innumisfull = 0while outnum > 0 and innum < n * m:    if isfull == 0:        shortest_len = m        for i in range(n):            if len(window[i]) < shortest_len:                shortest_len = len(window[i])                shortest_window = i    else:        shortest_window = pop_window    if len(window[shortest_window]) > 0:        window[shortest_window].append(window[shortest_window][-1] + process_time[0])    else:        window[shortest_window].append(process_time[0])    res.append(window[shortest_window][-1])    process_time.popleft()    innum += 1    outnum -= 1    isfull = 0    if innum == n * m and outnum > 0:        first_ones = []        for i in range(n):            first_ones.append(window[i][0])        min_time = min(first_ones)        pop_window = first_ones.index(min_time)        window[pop_window].popleft()        isfull = 1        innum -= 1result = list(map(totime, res))for i in range(q):    # if qlist[i] <= len(result):    #   print(result[qlist[i] - 1])    # else:    #   print('Sorry')    if res[qlist[i] - 1] - process[qlist[i] - 1] < 540:        print(result[qlist[i] - 1])    else:        print('Sorry')
  1. 思路:使用双向操作列表,将每个窗口最前面的人中,最早结束的popleft, 然后下次循环往这个队伍里面添加新的客户.
  2. collections.deque(a)建立可双向操作列表, 可直接深拷贝list_a.
  3. 注意审题,17:00能排上的应该输出服务结束时间而不是Sorry.

1015. Reversible Primes (20)

A reversible prime in any number system is a prime whose “reverse” in that number system is also a prime. For example in the decimal system 73 is a reversible prime because its reverse 37 is also a prime.

Now given any two positive integers N (< 105) and D (1 < D <= 10), you are supposed to tell if N is a reversible prime with radix D.

Input Specification:

The input file consists of several test cases. Each case occupies a line which contains two integers N and D. The input is finished by a negative N.

Output Specification:

For each test case, print in one line “Yes” if N is a reversible prime with radix D, or “No” if not.

Sample Input:
73 10
23 2
23 10
-2
Sample Output:
Yes
Yes
No

代码:

#-*- coding:utf-8 -*-#@author cxlualine = []while(1):    line.append([int(i) for i in input().split()])    if line[-1][0] < 0:        break# print(line)## 进制逆序 strdef toradix(num, d):    res = ''    while num != 0:        res += str(num % d)        num = num // d    return res## 十进制数 intdef todec(num, r):    res = 0    times = 0    while num != 0:        res += num % 10 * r ** times        times += 1        num = num // 10    return res## 判断素数def judgeprime(num):    if num == 2:        return True    elif num == 1:        return False    else:        for i in range(2, num):            if num % i == 0:                return False        return Truedef printstr(boolean):    if boolean == True:        return 'Yes'    else:        return 'No'for i in range(len(line) - 1):    reverse = toradix(line[i][0], line[i][1])    dec = todec(int(reverse), line[i][1])    print(printstr(judgeprime(dec) and judgeprime(line[i][0])))
  1. 素数要注意1和2单独考虑;(测试点2考虑了结果为1,应输出’No’);
  2. 逆序前后的数都要作素数判断,不只是逆序后的(测试点4);
  3. 题目审清楚,先换进制,再逆序,再换回十进制判读素数。

1016. Phone Bills (25)

A long-distance telephone company charges its customers by the following rules:

Making a long-distance call costs a certain amount per minute, depending on the time of day when the call is made. When a customer starts connecting a long-distance call, the time will be recorded, and so will be the time when the customer hangs up the phone. Every calendar month, a bill is sent to the customer for each minute called (at a rate determined by the time of day). Your job is to prepare the bills for each month, given a set of phone call records.

Input Specification:

Each input file contains one test case. Each case has two parts: the rate structure, and the phone call records.

The rate structure consists of a line with 24 non-negative integers denoting the toll (cents/minute) from 00:00 - 01:00, the toll from 01:00 - 02:00, and so on for each hour in the day.

The next line contains a positive number N (<= 1000), followed by N lines of records. Each phone call record consists of the name of the customer (string of up to 20 characters without space), the time and date (mm:dd:hh:mm), and the word “on-line” or “off-line”.

For each test case, all dates will be within a single month. Each “on-line” record is paired with the chronologically next record for the same customer provided it is an “off-line” record. Any “on-line” records that are not paired with an “off-line” record are ignored, as are “off-line” records not paired with an “on-line” record. It is guaranteed that at least one call is well paired in the input. You may assume that no two records for the same customer have the same time. Times are recorded using a 24-hour clock.

Output Specification:

For each test case, you must print a phone bill for each customer.

Bills must be printed in alphabetical order of customers’ names. For each customer, first print in a line the name of the customer and the month of the bill in the format shown by the sample. Then for each time period of a call, print in one line the beginning and ending time and date (dd:hh:mm), the lasting time (in minute) and the charge of the call. The calls must be listed in chronological order. Finally, print the total charge for the month in the format shown by the sample.

Sample Input:
10 10 10 10 10 10 20 20 20 15 15 15 15 15 15 15 20 30 20 15 15 10 10 10
10
CYLL 01:01:06:01 on-line
CYLL 01:28:16:05 off-line
CYJJ 01:01:07:00 off-line
CYLL 01:01:08:03 off-line
CYJJ 01:01:05:59 on-line
aaa 01:01:01:03 on-line
aaa 01:02:00:01 on-line
CYLL 01:28:15:41 on-line
aaa 01:05:02:24 on-line
aaa 01:04:23:59 off-line
Sample Output:
CYJJ 01
01:05:59 01:07:00 61 12.10Totalamount:12.10
CYLL 01
01:06:01 01:08:03 122 24.4028:15:4128:16:05243.85
Total amount: 28.25aaa0102:00:0104:23:594318638.80
Total amount: $638.80

代码:

#@author cxluaimport datetimerate = [int(i) for i in input().split()]n = int(input().split()[0])record = {}for i in range(n):    temp = input().split()    if temp[0] not in record.keys():        record[temp[0]] = {}        record[temp[0]][temp[1]] = temp[2]    else:        record[temp[0]][temp[1]] = temp[2]# print(record)month = temp[1][:2]for key in record.keys():    record[key] = sorted(record[key].items(), key = lambda x: (x[0].split(':')[0], x[0].split(':')[1], x[0].split(':')[2], x[0].split(':')[3]))    # print(key)    ############## 错误代码 #################    #isdel = 0    #for i in range(len(record[key])):        # print(i, record[key])        #if record[key][i - isdel][1] == 'on-line':            #if i - isdel == len(record[key]) - 1 or record[key][i - isdel + 1][1] != 'off-line':                #del record[key][i - isdel]                #isdel = 1        #else:            #if i - isdel == 0 or record[key][i - isdel - 1][1] != 'on-line':                #del record[key][i - isdel]                #isdel = 1        # print(i, key, record[key])    ################### 正确代码 ###############    delcount = 0    for i in range(len(record[key])):        # print(i, record[key])        if record[key][i - delcount][1] == 'on-line':            if i - delcount == len(record[key]) - 1 or record[key][i - delcount + 1][1] != 'off-line':                del record[key][i - delcount]                delcount += 1        else:            if i - delcount == 0 or record[key][i - delcount - 1][1] != 'on-line':                del record[key][i - delcount]                delcount += 1        # print(i, key, record[key])    ##########################################def pricesameday(on_time, off_time):    global rate    price = 0    if on_time.hour == off_time.hour:            price += (off_time.minute - on_time.minute) * rate[on_time.hour]    else:        price += (60 - on_time.minute) * rate[on_time.hour] + off_time.minute * rate[off_time.hour]        for i in range(1, off_time.hour - on_time.hour):            price += rate[on_time.hour + i] * 60        return pricetime = {}prices = {}for key in record.keys():    time[key] = []    prices[key] = []    for i in range(int(len(record[key]) / 2)):        on_time = datetime.datetime.strptime(record[key][2 * i][0], '%m:%d:%H:%M')        off_time = datetime.datetime.strptime(record[key][2 * i + 1][0], '%m:%d:%H:%M')        delta = off_time - on_time        time[key].append(int(delta.total_seconds() / 60))        price = 0 # in cent        if on_time.day == off_time.day:            price += pricesameday(on_time, off_time)        else:            price += pricesameday(on_time.time(), datetime.time(23, 59)) + 10            price += pricesameday(datetime.time(0,0), off_time.time())            if off_time.day - on_time.day > 1:                pricefullday = 0                for i in range(24):                    pricefullday += rate[i] * 60                price += (off_time.day - on_time.day - 1) * pricefullday        prices[key].append(price / 100.)  record = sorted(record.items(), key=lambda x: x[0])for user in record:    if len(user[1]) > 0:        print(user[0], month)        for j in range(int(len(user[1]) / 2)):            temp = user[1][2 * j][0][3:] + ' ' + user[1][2 * j + 1][0][3:] + ' ' + str(time[user[0]][j]) + ' $' + '%.02f'%prices[user[0]][j]            print(temp)        totalamount = sum(prices[user[0]])        print('Total amount: $' + '%.02f' % totalamount)
  1. datetime模块的使用,以及字符串化为时间.
  2. 关于在循环中删除列表元素的i值更新(代码中有正确错误注释的部分),计数器对删除元素个数计数,每个循环的索引要减去计数值.
  3. 浮点数在后面补零:’%.02f’%a, 得到类型为str.
原创粉丝点击