AtCoder Regular Contest 086 C - Not so Diverse Difficulty: 431
This theme, hash sorting Ruby Speaking of duplicate lists, it's hashes.
ruby.rb
n, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
h = Hash.new(0)
a.each do |x|
h[x] += 1
end
puts n - h.values.sort.reverse[0, k].inject(:+)
before.rb
h.sort_by{|key, v| -v}.each do |key, v|
after.rb
puts n - h.values.sort.reverse[0, k].inject(:+)
~~ * Ruby * doesn't have a destructive sort of hashes, but it seems to have few uses. ~~ ** Addition ** The original code was to sort the hashes, but in the comments I got the idea of taking the values side as an array, sorting, slicing and summing. Python
python.py
from collections import defaultdict
n, k = map(int, input().split())
a = list(map(int, input().split()))
h = defaultdict(int)
for x in a:
h[x] += 1
ans = 0
i = 0
for key, v in sorted(h.items(), key=lambda x: -x[1]):
i += 1
if i > k:
ans += v
print(ans)
sort.py
for key, v in sorted(h.items(), key=lambda x: -x[1]):
For * Python *, it's called a dictionary rather than a hash.
Also, many players are using Counter
instead of defaultdict
.
Perl
perl.pl
chomp (my ($n, $k) = split / /, <STDIN>);
chomp (my @a = split / /, <STDIN>);
my %h;
$h{$_}++ for @a;
my ($c, $ans) = (0, 0);
for my $v (sort {$b <=> $a} values %h) {
$c++;
$ans += $v if $c > $k;
}
print "$ans\n";
sort.pl
for my $v (sort {$b <=> $a} values %h) {
Sorting * Perl * is simple. Java
java.java
import java.util.*;
import java.util.stream.Collectors;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.next());
int k = Integer.parseInt(sc.next());
HashMap<Integer, Integer> h = new HashMap<>();
for (int i = 0; i < n; i++) {
int a = Integer.parseInt(sc.next());
h.merge(a, 1, Integer::sum);
}
sc.close();
List<Integer> s = new ArrayList<>(h.values());
Collections.sort(s);
int ans = 0;
for (int i = s.size() - k - 1; i >= 0; i--) {
ans += s.get(i);
}
System.out.println(ans);
}
}
sort.java
List<Integer> s = new ArrayList<>(h.values());
Collections.sort(s);
For * Java *, it is converted to a list and sorted. ** Addition ** I modified the code from the comments.
Ruby | Python | Perl | Java | |
---|---|---|---|---|
Code length | 156 Byte | 286 Byte | 226 Byte | 723 Byte |
Execution time | 187 ms | 261 ms | 214 ms | 620 ms |
memory | 32880 KB | 39352 KB | 46668 KB | 70772 KB |
Referenced site
Recommended Posts