|
- DPµÄ×ö·¨ÊǵäÐ͵ĵı³°üÎÊÌâ±äÐΣ¬ÈôÉèf[i][j]ΪǰÃæi±¾Êé·Ö³Éj¸öÈ˳ʱµÄ×îÉÙʱ¼ä£¬s[i][j]Ϊһ¸ö³µÚiµ½µÚj±¾ÊéµÄʱ¼ä£¬ÔòתÒÆ·½³Ì¡°
- f[i][1]=s[1][i]
- f[i][j]=min(f[i-k][j-1]+s[i-k+1][i])
- ¿´µÃ³öÕâ¸öתÒÆ·½³ÌºÍ±³°üÎÊÌâºÜÏàËÆ£¬Ì×ÓÃÄǸö³ÌÐòµÄ¿ò¼Ü¼´¿É¡£
- // 1 3 7 8 9 2 4 5 6¾Å¸öÊý×Ö°´Ë³Ðò·Ö³ÉÈý¶Ñ£¬Ê¹×î´óµÄÄÇÒ»¶Ñ×îС
- #include <iostream>
- #include <iomanip>
- using namespace std;
- int a[10]= {0,1,2,3,4,5,6,7,8,9}; //Ê®¶ÑÔʼÊý¾Ý
- int s[10][10]; //s[i][j]±íʾµÚi¶Ñµ½µÚj¶Ñ¹²ÓжàÉÙ¸ö DP³õʼ״̬ ²»»®·ÖµÄÇé¿ö
- int f[10][4]; //f[i][j]Ç°i¸öʯͷ±»·Ö³Éj¶ÑµÃ×îСֵ DP״̬
- int w[10][4]; //»®·Öµã£¬¾ö²ß·½·¨
- int i,j,k,t1,t2,t,m,p;
- int main()
- {
- for (i=1; i<=9; i++)
- {
- s[i][i]=a[i];
- for (j=i+1; j<=9; j++) s[i][j]=s[i][j-1]+a[j];
- }
- //Êä³ö¼ì²éÏÂ
- cout<<"================s====\n";
- for (i=1; i<=9; i++)
- {
- for (j=1; j<=9; j++) cout<<setw(4)<<s[i][j];
- cout<<endl;
- }
- //³õʼ״̬ ²»»®·ÖµÄ»°¾ÍÊÇÖ±½Ó¼Ó
- for (i=1; i<=9; i++) f[i][1]=s[1][i];
- for (j=2; j<=3; j++) //·Ö³É2¶Ñ¿ªÊ¼ ×¢Òâö¾Ù˳Ðò
- for (i=j; i<=9; i++) //iÏÔȻҪ´óÓÚj
- {
- m=9999; //×îСֵ³õÖµ
- for (k=j-1; k<=i-1; k++) //ö¾Ù»®·Öµã ×¢ÒâÈ¡Öµ·¶Î§£¡£¡£¡
- {
- t1=f[k][j-1]; //Ç°ÃæÒ»¶Î k¸öÊý×Ö·Ö³Éj-1·Ý
- t2=s[k+1][i]; //ºóÃæÒ»¶Î ×Ô³ÉÒ»¶Î
- if (t1>t2) t=t1;
- else t=t2;//È¡×î´óÖµ
- if (t<m) m=t,p=k; //¼Ç¼×îСֵºÍλÖÃ
- }
- f[i][j]=m,w[i][j]=p; //DP¸üÐÂÖµ
- }
- //¼ì²éfÊý×é
- cout<<"================f====\n";
- for (j=1; j<=3; j++)
- {
- for (i=1; i<=9; i++) cout<<setw(4)<<f[i][j];
- cout<<endl;
- }
- cout<<f[9][3]<<endl;
- cout<<"================w====\n";
- for (j=1; j<=3; j++)
- {
- for (i=1; i<=9; i++) cout<<setw(4)<<w[i][j];
- cout<<endl;
- }
- cout<<f[9][3]<<endl;
- }
¸´ÖÆ´úÂë |
|