我遇到類似於此任務的問題: click (translated)(我分配的那個測試的方法更大,時間更短)。任務的快速翻譯:在perl中發生SPOJ發生的速度問題
編寫一個程序,檢查給定序列中發生給定數量的次數。
輸入:給定數量,有多少數字序列中,數字序列
輸出:
我的解決方案,到目前爲止出現的次數:
1:
#!/usr/bin/env perl
while (<>) {
$in = $_;
@nums = split//, $in, 3;
$what = shift @nums;
shift @nums;
$rest = shift @nums;
$rest = " ".$rest." ";
$sum =() = $rest =~ /(?<=\s)$what(?=\s)/g;
print $sum;
print "\n";
}
2:
#!/usr/bin/env perl
while (<>) {
$in = $_;
@nums = split//, $in, 3;
$what = shift @nums;
shift @nums;
$rest = shift @nums;
$rest = " ".$rest." ";
if(!$reg{$what}){
$reg{$what} = qr/(?<=\s)$what(?=\s)/;
}
$sum =() = $rest =~ /$reg{$what}/g;
print $sum;
print "\n";
}
我也嘗試了強制方法,哈希表,grep的...所有超過給定的時間限制,我有不知道如何寫東西,將工作速度比上述兩種。有任何想法嗎?
編輯:後襬脫複製列表(原來的數字也可以是負的):
#!/usr/bin/env perl
while ($line = <>) {
$line =~ s/^(-?\d+) \d+//;
$what = $1;
$sum =() = $line =~/$what\b/g;
print $sum;
print "\n";
}
EDIT2:通過http://www.chengfu.net/2005/10/count-occurrences-perl/:
print $sum = (($line =~ s/ $1\b//g)+0);
導致了快2倍代碼比:
print $sum =() = $line =~/$1\b/g;
現在工作,謝謝:)
數據集有多大?什麼時間限制? :) – Orbit 2011-03-03 00:34:04
spoj測試是祕密的,但我有一個示例測試,每行有1k行和600個數字。時間限制爲1秒。我沒有辦法檢查上面兩個在spoj上運行多久:( – 2011-03-03 00:37:57