các thuật toán cơ bản trong lập trình

Upload: thanh-nguyen

Post on 08-Jul-2015

413 views

Category:

Documents


16 download

TRANSCRIPT

Kim tra 1 s nguyn t+ nh ngha: L s nguyn ln hn 1, ch c 2 c l 1 v chnh n. Cc s nguyn t t 1100: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 + Thut ton: kim tra 1 s nguyn n c phi s nguyn t hay khng, ta lm theo cc bc. - Nu n> KMP("abcabcabcabc", "cabc") Match at position 2 Match at position 5 Match at position 8

im th v cui cng l, mi k t ca chui s c so snh vi nhiu nht l gi l delay ca thut ton), trong l t l vng! + Code hon chnh: Visual C# Code: using System; namespace Knuth_Morris_Pratt { class Test { private char[] s; private char[] p; public void Nhap() { Console.Write("Nhap xau S:"); string stdin1 = Console.ReadLine(); s = new char[stdin1.Length]; s = stdin1.ToCharArray(); Console.Write("Nhap xau P:"); string stdin2 = Console.ReadLine(); p = new char[stdin2.Length]; p = stdin2.ToCharArray(); }

(i lng ny

private int[] compute_MP_map() // map[i]=| border(p[0..i-1]) | { int m = p.Length; // p is the input pattern int[] MP_map = new int[m + 1]; // lu rng ta phi tnh map[0..m] // init MP_map[0] = -1; // ci ny chc ai cng hiu // bay gio di tinh map[1..m] int i = 0; int j = MP_map[i]; while (i < m) { while (j >= 0 && (p[i] != p[j])) j = MP_map[j]; j++; i++; MP_map[i] = j; } return MP_map; } private int[] compute_KMP_map() //thut ton KMP ci tin { int m = p.Length; int[] KMP_map = new int[m + 1]; int[] MP_map = compute_MP_map(); KMP_map[0] = -1; KMP_map[m] = MP_map[m]; for (int i = 1; i < m; i++) { int j = MP_map[i]; if (p[i] != p[j]) KMP_map[i] = j; else KMP_map[i] = MP_map[j]; } return KMP_map; } public void Morris_Pratt() { int[] map = compute_KMP_map();

int n = s.Length; int m = p.Length; int i = 0; string res = ""; for (int j = 0; j < { while ((i >= 0) i++; (i=m-1) hoc l i=-1 , li dng if (i == m) { res += (j i = map[i]; } } Console.Write(res); }

n; j++) && (p[i] != s[j])) i = map[i]; // C 2 kh nng xy ra: hoc l i ht chui p c 2 iu ny m + 1).ToString() + " ";

static void Main(string[] args) { Test object1 = new Test(); object1.Nhap(); object1.Morris_Pratt(); //Console.WriteLine("done"); Console.ReadLine(); } } }

Lit k dy nh phn c di n+ V d: n=3 ta c cc dy nh phn nh sauCode:

0 0 0 0 1 1 1 1

0 0 1 1 0 0 1 1

0 1 0 1 0 1 0 1

+ Tc gi: CayDan + Code: - Phng php sinh: C Code: void LKNhiPhan(int n) { int x[30]; for (int i=0; i=0) { for (i=0; i=0) && (x[i] == 1)) i--; if(i>=0) { x[i] = 1; for (int j= i+1; j