PTA

PTA

11.1课后题

7-2 通讯录排序(20 分)

输入n个朋友的信息,包括姓名、生日、电话号码,本题要求编写程序,按照年龄从大到小的顺序依次输出通讯录。题目保证所有人的生日均不相同。

输入格式:

输入第一行给出正整数n(10)。随后n行,每行按照“姓名 生日 电话号码”的格式给出一位朋友的信息,其中“姓名”是长度不超过10的英文字母组成的字符串,“生日”是yyyymmdd格式的日期,“电话号码”是不超过17位的数字及+-组成的字符串。

输出格式:

按照年龄从大到小输出朋友的信息,格式同输出。

输入样例:

3
zhang 19850403 13912345678
wang 19821020 +86-0571-88018448
qian 19840619 13609876543

输出样例:

 wang 19821020 +86-0571-88018448
qian 19840619 13609876543
zhang 19850403 13912345678

C++

#include <iostream>  
#include <algorithm>  
#include <vector>  
#include <string>
using namespace std;
class Friend
{
public:
	int brithday;
	Friend(string name,int brithday,string phone)
	{
		this->name = name;
		this->brithday = brithday;
		this->phone = phone;
	}
	string display()
	{
		return name + " " + Brithday() + " " + phone;
	}
private:
	string name;
	string phone;
	string Brithday()
	{
		return to_string(brithday);
	}
};
bool cmp(const Friend &t1, const Friend &t2)
{
	return t1.brithday < t2.brithday ? true : false;
}
int main()
{
	int count;
	cin >> count;
	vector<Friend> friends;
	for (int i = 0; i < count; ++i)
	{
		string name, phone;
		int brithday;
		cin >> name >> brithday >> phone;
		friends.push_back(Friend(name, brithday, phone));
	}
	sort(friends.begin(), friends.end(), cmp);
	for (int i = 0; i < count; ++i)
	{
		cout << friends[i].display() << endl;
	}
	return 0;
}

 

7-1 查找书籍(20 分)

给定n本书的名称和定价,本题要求编写程序,查找并输出其中定价最高和最低的书的名称和定价。

输入格式:

输入第一行给出正整数n(10),随后给出n本书的信息。每本书在一行中给出书名,即长度不超过30的字符串,随后一行中给出正实数价格。题目保证没有同样价格的书。

输出格式:

在一行中按照“价格, 书名”的格式先后输出价格最高和最低的书。价格保留2位小数。

输入样例:

3
Programming in C
21.5
Programming in VB
18.5
Programming in Delphi
25.0

输出样例:

25.00, Programming in Delphi
18.50, Programming in VB

Python3

books={}
for i in range(0,int(input())):
    books[input()]=input()
print("%.2f, %s\n%.2f, %s" % ((float(sorted(books.keys())[-1])),(books[list(sorted(books.keys()))[-1]]),(float(sorted(books.keys())[0])),(books[list(sorted(books.keys()))[0]])))

C

#pragma warning (disable:4996)
#include<stdio.h>
#include<stdlib.h>
#include<stdint.h>
#include<string.h>
typedef struct book
{
	char name[100];
	float price;
}book;
int compare(const void *a, const void *b)
{
	return (*(book *)a).price > (*(book *)b).price ? 1 : -1;
}
int main()
{
	int count;
	scanf("%d", &count);
	if (count > 0)
	{
		struct book *books = (struct book *)malloc(sizeof(struct book)*count);
		getchar();
		for (uint8_t i = 0; i < count; ++i)
		{
			fgets(books[i].name, 33, stdin);
			books[i].name[strlen(books[i].name) - 1] = '\0';
			scanf("%f", &books[i].price);
			getchar();
		}
		qsort(books, count, sizeof(books[0]), compare);
		if (count == 1)
		{
			printf("%.2f, %s\n%.2f, %s", books[0].price, books[0].name, books[0].price, books[0].name);
		}
		else
		{
			printf("%.2f, %s\n%.2f, %s", books[count - 1].price, books[count - 1].name, books[0].price, books[0].name);
		}
	}
	else
	{
		printf("0.00, \n0.00, \n");
	}
	return 0;
}

C++

#include <iostream>  
#include <algorithm>  
#include <vector>  
#include <iomanip>
#include <string>
using namespace std;
class Book 
{
public:
	string name;
	float price;
	Book(bool red)
	{
		getline(cin, name);
		cin >> price;
		getchar();
	}
};
bool cmp(const Book &t1, const Book &t2)
{
	return t1.price > t2.price ? true : false;
}
int main(int argc, char *argv[])
{
	vector<Book> books;
	int count;
	cin >> count;
	if (count <= 0)
	{
		cout << "0.00, \n0.00 ";
		return 0;
	}
	getchar();
	for (int i = 0; i < count; ++i)
	{
		books.push_back(Book(true));
	}
	sort(books.begin(), books.end(), cmp);
	cout << setiosflags(ios::fixed) << setprecision(2) << books[0].price << ", " + books[0].name << endl << setiosflags(ios::fixed) << setprecision(2) << books[books.size() - 1].price << ", " + books[books.size() - 1].name;
	return 0;
}

Java

import java.util.*;
public class Main 
{
	public static void main(String[] args) 
	{
        Scanner inpu=new Scanner(System.in);
        int count = Integer.parseInt(inpu.nextLine());
        String maxn="",minn="";
        double minp=100000000,maxp=0;
        for(int i=0;i<count;++i)
        {
        	String inn=inpu.nextLine();
        	double inp=Double.parseDouble(inpu.nextLine());
        	if(inp>maxp)
        	{
        		maxp=inp;
        		maxn=inn;
        	}
        	if(inp<minp)
        	{
        		minp=inp;
        		minn=inn;
        	}
        }
        System.out.println(String.format("%.2f", maxp)+", "+maxn);
        System.out.println(String.format("%.2f", minp)+", "+minn);
	}
}

C#

using static System.Console;
using static System.Convert;
using System.Collections.Generic;
using System.Linq;
using System;
namespace TEMP_CS
{
    public class Book
    {
        private string name;
        private double price;
        public Book(string name,double price)
        {
            this.name = name;
            this.price = price;
        }
        public string Name { get => name;}
        public double Price { get => price;}
        public bool Display()
        {
            WriteLine($"{String.Format("{0:F}", Price)}, {Name}");
            return true;
        }
    }
    public class Program
    {
        public static void Main()
        {
            List<Book> books = new List<Book>();
            int count = ToInt32(ReadLine());
            for(int i=0;i<count;++i)
            {
                books.Add(new Book(ReadLine(), ToDouble(ReadLine())));
            }
            books.OrderBy(book => book.Price).Reverse().ToList()[0].Display();
            books.OrderBy(book => book.Price).ToList()[0].Display();
        }
    }
}

C++/CLI

using namespace System;
int main(array<System::String ^> ^args)
{
	int count = Convert::ToInt32(Console::ReadLine());
	String^ maxn, ^minn;
	double maxp = 0, minp = 1000000;
	for (int i = 0; i < count; ++i)
	{
		String^ inn = Console::ReadLine();
		double inp = Convert::ToDouble(Console::ReadLine());
		if (inp>maxp)
		{
			maxp = inp;
			maxn = inn;
		}
		if (inp<minp)
		{
			minp = inp;
			minn = inn;
		}
	}
	Console::WriteLine(String::Format(L"{0:F}", maxp) + ", " + maxn);
	Console::WriteLine(String::Format(L"{0:F}", minp) + ", " + minn);
    return 0;
}

F#

open System
let count = Convert.ToInt32(Console.ReadLine())
type book = {name:string;price:float}
let mutable max = {name="";price=0.0}
let mutable min = {name="";price=1000000.0}
for i = 1 to count do
    let input = {name=Console.ReadLine();price=Convert.ToDouble(Console.ReadLine())}
    if input.price>max.price then
        max<-input
    if input.price<min.price then 
        min<-input
Console.Write(String.Format("{0:F}",max.price)+", "+max.name+"\n"+String.Format("{0:F}",min.price)+", "+min.name)

【初赛】第五届程序设计大赛/7-1 A+B 输入输出练习 (VII)

g++

#include <iostream>

using namespace std;

int main()
{
  int a, b;
  while (cin >> a >> b) cout << a+b << endl << endl;
  return 0;
}

【初赛】第五届程序设计大赛/7-2 小Y系列之又见 a+b

g++

#include <iostream>

using namespace std;

int main()
{
  int a, b;
  while (cin >> a >> b) cout << a+b << endl;
}

【初赛】第五届程序设计大赛/7-4 哪几周有课

C#

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp2
{
    public class Program
    {
        public static void Main()
        {
            string line;
            while ((line = System.Console.ReadLine()) != null)
            {
                var lst = new List<int>();
                var tk = line.Split(',');
                foreach (var s in tk)
                {
                    if (s.Contains("-"))
                    {
                        var ttk = s.Trim().Split('-').Select(x => x.Trim()).Select(int.Parse).ToArray();
                        lst.AddRange(Enumerable.Range(ttk[0], ttk[1] - ttk[0] + 1));
                    }
                    else
                    {
                        lst.Add(int.Parse(s.Trim()));
                    }
                }
                lst.Sort();
                Console.WriteLine(string.Join(",", lst));
            }
        }
    }
}

【初赛】第五届程序设计大赛/7-10 进度条

g++

#include <cstdlib>
#include <iostream>
#include <string>
#include <cmath>

using namespace std;
int main()
{
	int x;
	cin >> x;
	srand(x);
	for (int i = 0; i < x; ++i)
	{
		auto r = 1 + rand() % 35;
		printf("%s%3d%%\n", (string(r, '>') + string(35 - r, '.')).c_str(), static_cast<int>(round(r / 35. * 100)));
	}
}

蓝桥杯练习1/7-3 莫尔斯码(Morse Code) (15分)

JavaScript

let codes = new Map(Object.entries({
    A: '.-', B: '-...', C: '-.-.', D: '-..', E: '.', F: '..-.',
    G: '--.', H: '....', I: '..', J: '.---', K: '-.-', L: '.-..',
    M: '--', N: '-.', O: '---', P: '.--.', Q: '--.-', R: '.-.',
    S: '...', T: '-', U: '..-', V: '...-', W: '.--', X: '-..-',
    Y: '-.--', Z: '--..', 0: '-----', 1: '.----', 2: '..---', 3: '...--',
    4: '....-', 5: '.....', 6: '-....', 7: '--...', 8: '---..', 9: '----.'
}));

let start = 0;

require('readline').createInterface({
    input: process.stdin
}).on('line', (line) => {
    if (start === 0) {
        start = +line;
    } else {
        console.log(/[.-]/.test(line) ? line.split('|').map(x => x.split(' ').map(y => [...codes].find(([_, v]) => v === y)[0]).join('')).join(' ') : line.split(' ').map(x => [...x].map(y => codes.get(y)).join(' ')).join('|'));
    }
});

蓝桥杯练习2/7-1 对称排序 (25分)

C++(g++)

@@ -0,0 +1,32 @@
#include <iostream>
#include <vector>
#include <iterator>

int main()
{
	int n, index = 1;
	while (true)
	{
		std::cin >> n;
		std::vector<std::string> data{};
		if (n==0)
		{
			exit(0);
		}
		for (auto i = 0; i < n; ++i)
		{
			std::string s;
			std::cin >> s;
			data.push_back(s);
		}
		std::cout << "SET " << index++ << "\n";
		for (auto i = 0; i < n; i+=2)
		{
			std::cout << data[i] << "\n";
		}
		for (auto i = ((n & 1) == 0 ? n - 1 : n - 2); i > 0; i -= 2)
		{
			std::cout << data[i] << "\n";
		}
	}
}

蓝桥杯练习2/7-2 德才论 (25分)

C++(g++)

#include <algorithm>
#include <iterator>
#include <iostream>
#include <queue>
#include <utility>

struct Fuck
{
	std::string s;
	int d;
	int c;
	int sum;
	Fuck(std::string s, const int d, const int c) :s(std::move(s)), d(d), c(c), sum(d + c) {}
};

auto Cmp = [](const Fuck& l, const Fuck& r)
{
	if (l.sum == r.sum)
	{
		if (l.d == r.d)
		{
			return l.s > r.s;
		}
		return l.d < r.d;
	}
	return l.sum < r.sum;
};

using PQ = std::priority_queue<Fuck, std::vector<Fuck>, decltype(Cmp)>;

int main()
{
	int n, l, h;
	PQ q0(Cmp);
	PQ q1(Cmp);
	PQ q2(Cmp);
	PQ q3(Cmp);
	std::cin >> n >> l >> h;
	for (auto i = 0; i < n; ++i)
	{
#define Emplace(q) q.push(Fuck(s, d, c))
		std::string s;
		int d, c;
		std::cin >> s >> d >> c;
		if (d >= h && c >= h)
		{
			Emplace(q0);
		}
		else if (d >= h && c >= l)
		{
			Emplace(q1);
		}
		else if (d >= l && c >= l && d >= c)
		{
			Emplace(q2);
		}
		else if (d >= l && c >= l)
		{
			Emplace(q3);
		}
	}
	std::cout << q0.size() + q1.size() + q2.size() + q3.size() << "\n";
#define Print(q)\
		while (!(q).empty())\
		{\
			std::cout << (q).top().s << " " << (q).top().d << " " << (q).top().c << "\n";\
			(q).pop();\
		}
	Print(q0);
	Print(q1);
	Print(q2);
	Print(q3);
}

蓝桥杯练习2/7-3 利用STL比较数据大小并排序 (12分)

C++(g++)

#include <iostream>
#include <queue>

int main()
{
	std::priority_queue<int, std::vector<int>, std::greater<>> data{};
	int n;
	while (std::cin >> n) data.push(n);
	std::cout << u8"从标准设备读入数据,直到输入是非整型数据为止\n";
	while (!data.empty())
	{
		std::cout << " " << data.top();
		data.pop();
	}
}

蓝桥杯练习2/7-4 堆排序 (10分)

C++(g++)

#include <algorithm>
#include <iterator>
#include <iostream>
#include <vector>

int main()
{
	std::vector<int> data{};
	int n, x;
	std::cin >> n;
	for (int i = 0; i < n; ++i)
	{
		std::cin >> x;
		data.push_back(x);
	}
	std::make_heap(data.begin(), data.end());
	for (auto last = data.end(); last != data.begin(); --last)
	{
		std::copy(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, " "));
		std::cout << "\n";
		std::pop_heap(data.begin(), last);
	}
}

蓝桥杯练习2/7-5 查找书籍 (20分)

Python(python3)

list(map(lambda x:print("%.2f, %s" % (x[1],x[0])),(lambda x:[x[-1],x[0]])(sorted([(input(),float(input())) for i in range(int(input()))],key=lambda x:x[1]))))

蓝桥杯练习2/7-6 组织星期信息 (10分)

C++(g++)

#include <iostream>
#include <unordered_map>

int main()
{
	std::unordered_map<std::string, int> data
	{
		{"Sunday", 1},
		{"Monday", 2},
		{"Tuesday", 3},
		{"Wednesday", 4},
		{"Thursday", 5},
		{"Friday", 6},
		{"Saturday", 7}
	};
	int c;
	std::cin >> c;
	for (auto i = 0; i < c; ++i)
	{
		std::string s;
		std::cin >> s;
		auto t = data.find(s);
		std::cout << (t != data.end() ? t->second : -1) << "\n";
	}
}

蓝桥杯练习2/7-7 Sheldon的小本本 (10分)

Java

import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        List<String> data = new LinkedList<>();
        while (in.hasNextLine())
        {
            String[] s = in.nextLine().split(" ");
            if (s[0].equals("insert") && !data.contains(s[2]))
            {
                data.add(Integer.parseInt(s[1]) - 1,s[2]);
            }
            else if(s[0].equals("delete") && data.contains(s[1]))
            {
                data.remove(s[1]);
            }
            else if(s[0].equals("search") && data.contains(s[1]))
            {
                System.out.println(data.indexOf(s[1]) + 1);
            }
            else if(s[0].equals("show"))
            {
                System.out.println(String.join(" ", data) + " ");
            }
        }
    }
}

不给钱的比赛第5届/4.字符串

Java

import java.util.*;

public class Main
{
    public static void main(String... args)
    {
        System.out.println(Arrays.stream(new Scanner(System.in).nextLine().split("([ ])\\1*")).map(x -> x.substring(0, 1).toUpperCase() + x.substring(1)).map(x ->
        {
            if (x.matches("[A-Za-z]+")) return x;
            else
            {
                List<String> lst = new ArrayList<>();
                String[] ss = x.split("\\d+");
                int len = 0;
                for (int i = 0; i < ss.length; i++)
                {
                    if (!ss[i].equals("")) lst.add(ss[i]);
                    len += ss[i].length();
                    if (i != ss.length - 1) lst.add(x.substring(len, len + x.substring(len).indexOf(ss[i + 1])));
                }
                return String.join("_", lst);
            }
        }).reduce((a, b) -> a + " " + b).get());
    }
}

不给钱的比赛第5届/6.

Java

import java.util.*;
import java.util.function.Function;

public class Main
{
    public static void main(String... args)
    {
        Scanner scanner = new Scanner(System.in);
        int m = scanner.nextInt();
        int n = scanner.nextInt();
        final int me = 2 * m, ne = 2 * n;
        Function<String, Integer> f = x -> { System.out.print(x); return 0; };
        for (int i = 0; i < me + 1; i++)
        {
            for (int j = 0; j < ne + 1; j++)
            {
                if (i == 0)
                {
                    if (j == 0) f.apply("┌");
                    else if (j == ne) f.apply("┐");
                    else if ((j & 1) == 0) f.apply("┬");
                    else f.apply("─");
                }
                else if (i == me)
                {
                    if (j == 0) f.apply("└");
                    else if (j == ne) f.apply("┘");
                    else if ((j & 1) == 0) f.apply("┴");
                    else f.apply("─");
                }
                else if ((i & 1) == 1)
                {
                    f.apply((j & 1) == 0 ? "│" : "\u3000");
                }
                else
                {
                    if (j == 0) f.apply("├");
                    else if (j == ne) f.apply("┤");
                    else if ((j & 1) == 0) f.apply("┼");
                    else f.apply("─");
                }
            }
            f.apply("\n");
        }
    }
}

团体程序设计天梯赛-练习集/L1-001 Hello World

Pascal

begin
	writeln('Hello World!');
end.

ASM

section .data
msg db 'Hello World!', 0AH
len equ $-msg
 
section .text
global  main
main:
    mov edx, len
    mov ecx, msg
    mov ebx, 1
    mov eax, 4
    int 80h
 
    mov ebx, 0
    mov eax, 1
    int 80h

团体程序设计天梯赛-练习集/L1-002 打印沙漏

C#

using System.Linq;
using static System.Console;

namespace Program
{
    public class Program
    {
        public static void Main()
        {
            var cin = ReadLine().Split(' ');
            if (cin[0] == "1")
            {
                WriteLine(cin[1]);
                WriteLine(0);
                return;
            }
            int n;
            for (n = 0; Enumerable.Range(1, n + 1).Select(x => x * 2 - 1).Sum() * 2 - 1 < int.Parse(cin[0]); n++) ;
            foreach (var i in Enumerable.Range(2,n - 1).Reverse())
            {
                WriteLine("".PadRight(n - i) + "".PadRight(i * 2 - 1, cin[1][0]));
            }
            foreach (var i in Enumerable.Range(1, n))
            {
                WriteLine("".PadRight(n - i) + "".PadRight(i * 2 - 1, cin[1][0]));
            }

            WriteLine(int.Parse(cin[0]) - (Enumerable.Range(1, n).Select(x => x * 2 - 1).Sum() * 2 - 1));
        }
    }
}

团体程序设计天梯赛-练习集/L1-003 个位数统计

Python3

from collections import Counter
[print(str(k) + ':' + str(v)) for k,v in sorted(Counter(input()).items(), key=lambda pair: pair[0])]

团体程序设计天梯赛-练习集/

L1-004 计算摄氏温度

Racket

#lang racket
(printf "Celsius = ~a" (inexact->exact (floor (/ (* 5 (- (read) 32)) 9))))

团体程序设计天梯赛-练习集/L1-005 考试座位号

C++

#include <iostream>

using namespace std;

uint64_t ids[1001] = { 0 };
uint16_t indexs[1001] = { 0 };

int main()
{
	int n;
	cin >> n;
	for (auto i = 0; i < n; ++i)
	{
		uint64_t id;
		uint16_t key, val;
		cin >> id >> key >> val;
		ids[key] = id;
		indexs[key] = val;
	}
	cin >> n;
	for (auto i = 0; i < n; ++i)
	{
		int m;
		cin >> m;
		cout << ids[m] << " " << indexs[m] << endl;
	}
}

 

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注