2011-03-03 67 views
0

我遇到類似於此任務的問題: 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; 

現在工作,謝謝:)

+0

數據集有多大?什麼時間限制? :) – Orbit 2011-03-03 00:34:04

+0

spoj測試是祕密的,但我有一個示例測試,每行有1k行和600個數字。時間限制爲1秒。我沒有辦法檢查上面兩個在spoj上運行多久:( – 2011-03-03 00:37:57

回答

3

首先,你做了很多複製。我每次標記你在你的第一個例子複製大串時間:

while (<>) { 
    $in = $_;     # COPY 
    @nums = split//, $in, 3; # COPY 

    $what = shift @nums; 
    shift @nums; 
    $rest = shift @nums;  # COPY 
    $rest = " ".$rest." ";  # COPY 

    $sum =() = $rest =~ /(?<=\s)$what(?=\s)/g; 

    print $sum; 
    print "\n"; 
} 

爲了加快速度,避免了拷貝。例如,使用while ($in = <>)(或跳過$in並使用$_)。

對於提取$what和計數,我想我會嘗試這個,而不是split

$in =~ s/^(\d+) \d+//; 
$what = $1; 

加空格前後相反的,只是使用\b代替lookarounds與\s

$sum =() = $in =~ /\b$what\b/g; 
+0

謝謝!不幸的是,它仍然太慢;( – 2011-03-03 09:01:04