AtCoder Beginner Contest 131 D - Megalomania Difficulty: 594
Ce thème, tri des tableaux Ruby C'est une sorte de tableau, donc je pense que c'est facile à mettre en œuvre. ~~ Puisque c'est mon premier Python, j'ai choisi une question plus légère. ~~
ruby.rb
n = gets.to_i
a = Array.new(n){gets.split.map(&:to_i)}
a.sort_by!{|x| x[1]}
ans = 0
n.times do |i|
ans += a[i][0]
if ans > a[i][1]
puts "No"
exit
end
end
puts "Yes"
sort.rb
a.sort_by!{|x| x[1]}
~~ Tri selon plusieurs conditions, mais à des fins d'apprentissage, une seule peut être triée comme solution. ~~ ** Addenda ** Certaines corrections ont été apportées aux commentaires reçus. Python C'est presque une copie car c'est résolu avec *** Python *** pour la première fois.
python.py
n = int(input())
a = list(list(map(int, input().split())) for _ in range(n))
a.sort(key=lambda x: x[1])
ans = 0
for i in range(0, n):
ans += a[i][0]
if ans > a[i][1]:
print("No")
exit()
print("Yes")
Le codage est facile car l'extension VSCode fonctionne.
range.py
for i in range(0, n):
for i in range(0, n - 1):
J'ai essayé de le tourner avec i à for, mais j'ai écrit n -1 et j'ai obtenu WA.
La prochaine fois, j'essaierai de trier selon plusieurs conditions. Perl
perl.pl
chomp (my $n = <STDIN>);
my @a;
for my $i (0..$n-1) {
my @in = split / /, <STDIN>;
($a[$i][0], $a[$i][1]) = @in;
}
@a = sort {$$a[1]<=>$$b[1] || $$b[0]<=>$$a[0]} @a;
my $ans = 0;
for my $i (0..$n-1) {
$ans += $a[$i][0];
if ($ans>$a[$i][1]) {
print "No\n";
exit;
}
}
print "Yes\n";
sort.pl
@a = sort {$$a[1]<=>$$b[1] || $$b[0]<=>$$a[0]} @a;
java.java
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.next());
List<Work> work = new ArrayList<>();
for (int i = 0; i < n; i++) {
int time = Integer.parseInt(sc.next());
int limit = Integer.parseInt(sc.next());
work.add(new Work(time, limit));
}
sc.close();
work.sort(Comparator.comparingInt(x -> x.limit));
int ans = 0;
for (int i = 0; i < n; i++) {
ans += work.get(i).time;
if (ans > work.get(i).limit) {
System.out.println("No");
return;
}
}
System.out.println("Yes");
}
static class Work {
int time;
int limit;
Work(int time, int limit) {
this.time = time;
this.limit = limit;
}
}
}
sort.java
work.sort(Comparator.comparingInt(x -> x.limit));
** Addenda ** Comme on m'a dit dans les commentaires, j'ai changé la partie de comparaison de tri par le code qui utilise Comparator introduit dans java8. Plus sûr et légèrement plus rapide.
| Ruby | Python | Perl | Java | |
|---|---|---|---|---|
| Longueur du code | 189 Byte | 231 Byte | 315 Byte | 972 Byte |
| Temps d'exécution | 484 ms | 995 ms | 1237 ms | 883 ms |
| Mémoire | 22520 KB | 53728 KB | 66788 KB | 72900 KB |
Recommended Posts