贪心大法的几个问题
求最小生成樹的Prim算法和Kruskal算法都是漂亮的貪心算法。
貪心法的應用算法有Dijkstra的單源最短路徑和Chvatal的貪心集合覆蓋啟發式 貪心算法可以與隨機化算法一起使用,具體的例子就不再多舉了。 很多的智能算法(也叫啟發式算法),本質上就是貪心算法和隨機化算法結合。 這樣的算法結果雖然也是局部最優解,但是比單純的貪心算法更靠近了最優解。 例如遺傳算法,模擬退火算法。一.把3/7和13/23分別化為三個單位分數的和
設a、b為互質正整數,a<b 分數a/b 可用以下的步驟分解成若干個單位分數之和: 步驟一: 用b 除以a,得商數q1 及余數r1。(r1=b - a*q1) 步驟二:把a/b 記作:a/b=1/(q1+1)+(a-r1)/b(q1+1) 步驟三:重復步驟2,直到分解完畢 3/7=1/3+2/21=1/3+1/11+1/231 13/23=1/2+3/46=1/2+1/16+1/368 斐波那契的求解埃及分數的貪心算法: 設某個真分數的分子為a,分母為b; 把b除以a的商部分加1后的值作為埃及分數的某一個分母c; 將a乘以c再減去b,作為新的a; 將b乘以c,得到新的b; 如果a大于1且能整除b,則最后一個分母為b/a;算法結束; 或者,如果a等于1,則,最后一個分母為b;算法結束; 否則重復上面的步驟。 二.POJ 3377:Best Cow Line, Gold?貪心+字典序 題目: 總時間限制: 10000ms 單個測試點時間限制: 1000ms 內存限制: 65536kB 描述FJ is about to take his N (1 <= N <= 30,000) cows to the annual "Farmer of the Year" competition. In this contest every farmer arranges his cows in a line and herds them past the judges.The contest organizers adopted a new registration scheme this year: simply register the initial letter of every cow in the order they will appear (e.g., If FJ takes Bessie, Sylvia, and Dora in that order, he just registers BSD). After the registration phase ends, every group is judged in increasing lexicographic order (i.e., alphabetical order) according to the string of the initials of the cows' names.FJ is very busy this year and has to hurry back to his farm, so he wants to be judged as early as possible. He decides to rearrange his cows, who have already lined up, before registering them.FJ marks a location for a new line of the competing cows. He then proceeds to marshal the cows from the old line to the new one by repeatedly sending either the first or last cow in the (remainder of the) original line to the end of the new line. When he's finished, FJ takes his cows for registration in this new order.Given the initial order of his cows, determine the least lexicographic string of initials he can make this way.輸入* Line 1: A single integer: N* Lines 2..N+1: Line i+1 contains a single initial ('A'..'Z') of the cow in the ith position in the original line輸出The least lexicographic string he can make. Every line (except perhaps the last one) contains the initials of 80 cows ('A'..'Z') in the newline.樣例輸入 6 A C D B C B 樣例輸出ABCBCD View Code示例片段:
1 int n; 2 char s[maxl+1]; 3 void solve() 4 { 5 int a=0,b=n-1; 6 while(a<=b) 7 { 8 bool left=false; 9 for(int i=0;i+a<=b;i++) 10 { 11 if(s[a+i]<s[b_i]) 12 { 13 left=true; 14 break; 15 } 16 else if(s[a+i]>s[b_i]) 17 { 18 left=false; 19 break; 20 } 21 } 22 if(left){putchar(s[a++];)} 23 else putchar(s[b--];) 24 } 25 putchar('\n'); 26 } View Code原序取反,正反比較每次取出小的字符輸出即字典序排列,字典序比較常用得到貪心算法。
?
轉載于:https://www.cnblogs.com/dzzy/p/4711352.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
- 上一篇: 计组之中央处理器:5、微程序控制器(组成
- 下一篇: 计组之中央处理器:2、指令周期数据流(指