AtCoder Beginner Contest 131 D - Megalomania Difficulty: 594
This theme, sorting of arrays Ruby It's an array sort, so I think it's easy to implement. ~~ I chose a lighter question because it's my first Python. ~~
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]}
~~ Sorting is done by multiple conditions, but for learning purposes, only one can be sorted as a solution. ~~ ** Addition ** Some corrections have been made from the comments received. Python It is almost a sutra copy because it is solved with *** Python *** for the first time.
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")
Coding is easy because the VSCode extension is working.
range.py
for i in range(0, n):
for i in range(0, n - 1):
I tried to turn it with i at for, but I wrote n -1 and got WA
.
Next time, I will try to sort by multiple 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));
** Addition ** As I was told in the comments, I changed the sort comparison part to code that uses the Comparator introduced in java8. Safer and slightly faster.
Ruby | Python | Perl | Java | |
---|---|---|---|---|
Code length | 189 Byte | 231 Byte | 315 Byte | 972 Byte |
Execution time | 484 ms | 995 ms | 1237 ms | 883 ms |
memory | 22520 KB | 53728 KB | 66788 KB | 72900 KB |
Recommended Posts