120 likes | 260 Views
MOI 培訓班提高組 矩陣 -2. 澳門電腦學會. 常見的矩陣算法. 搜索 Matching 最大和子序列. 二分搜索. Search (key , n) VAR high, j, low : integer; found: boolean; BEGIN low := 0; high := n; found := false; WHILE (high-low > 1) AND NOT found DO BEGIN j := (high+low) div 2; IF key=r[j].k THEN
E N D
MOI 培訓班提高組矩陣-2 澳門電腦學會
常見的矩陣算法 • 搜索 • Matching • 最大和子序列
二分搜索 Search (key , n) VAR high, j, low : integer; found: boolean; BEGIN low := 0; high := n; found := false; WHILE (high-low > 1) AND NOT found DOBEGIN j := (high+low) div 2; IF key=r[j].k THEN found := true ELSE IF key <= r[j].k THEN high := j ELSE low := j END; IF found OR (r[high].k = key) THEN search := high ELSE search := -1; END;
簡單算法 gcatcgcagtgagtgcagagagtacagtacg gcagagag gcatcgcagtgagtgcagagagtacagtacg gcagagag gcagagag gcagagag gcagagag gcagagag gcagagag gcagagag gcagagag …
較好的算法 gcatcgcagtgagtgcagagagtacagtacg gcagagag gcatcgcagtgagtgcagagagtacagtacg gcagagag gcagagag gcagagag gcagagag gcagagag
BuildShift (p, m) FOR c:=‘a’ TO ‘z’ DO shift[c] := m; FOR i:=1 TO m DO shift[p[i]] := i;
Matching (a, n, p, m) i:=m; j:=m; WHILE i<=n DO WHILE j>0 AND a[i-j+m]=p[j] DO j:=j-1; IF j>0 THEN s := j-shift[a[i-j+m]]; IF s <0 THEN s:=1; i:=i+s; j:=m; ELSE Output(i-m); i:=i+1; j:=m;
Boyer-Moore Algorithm void BM(char *x, int m, char *y, int n) { int i, j, bmGs[XSIZE], bmBc[ASIZE]; preBmGs(x, m, bmGs); preBmBc(x, m, bmBc); j = 0; while (j <= n - m) { for (i = m - 1; i >= 0 && x[i] == y[i + j]; i=i-1); if (i < 0) { OUTPUT(j); j += bmGs[0]; } else j += MAX(bmGs[i], bmBc[y[i + j]] - m + 1 + i); } }
最大和子數列 • 在一個數列中, 找出一段連續的子數列, 使其和為可能的子數列中最大者 • 例: 2, 3, -2, 4, -10, 4, -2, 8, 7, 5, -23, 11, 7 2, 3, -2, 4, -10,4, -2, 8, 7, 5, -23, 11, 7
MaxSumSeq(s, n) start :=1; sum:=s[1]; MaxSum:=sum; MaxStart:=start; FOR i:=2 TO n DO IF sum<=0 THEN start := i; sum := MAX(sum,0)+s[i]; IF sum > MaxSum THEN MaxSum := sum; MaxStart := start;