题目:给出两个长度分别为n1,n2(n1,n2<=100)且每列高度只为1或2的长条。需要将它们放入一个高度为3的容器,问能够容纳它们的最短容器长度
思路: 从左到右依次检查,再将数组翻转
这里似乎有点小问题,考虑所有的翻转情况,上下数组移动情况时,会出现比标准答案更小的结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
#include<iostream> #include<cstring> using namespace std; int cal(char bottom[],char top[]){ char temp_b[202]="",temp_t[202]=""; strcpy(temp_b,bottom); strcpy(temp_t,top); int blen=strlen(temp_b),tlen=strlen(temp_t); int i=0; while(1){ bool key=1; for(int j=0;j<tlen;j++){ if(i+j==blen){ strcat(temp_b,"0"); blen++; continue; } if(temp_b[i+j]+temp_t[j]>'3'+'0'){ key=0; break; } } if(key){ /* for(int k=0;k<i;k++) cout << " "; cout << temp_t << endl << temp_b; cout << endl <<"num=" << blen << endl; */ return blen; } i++; } } void re(char str[]){ int len=strlen(str); for(int i=0,j=len-1;i<j;i++,j--){ char tem=str[i]; str[i]=str[j]; str[j]=tem; } } int main(){ char bottom[101]="",top[101]=""; while(cin >> bottom >> top){ /* int min=201,tem; for(int i=0;i<2;i++){ for(int j=0;j<2;j++){ tem=cal(bottom,top); min=(min<tem)? min:tem; re(top); } re(bottom); } cout << min << endl; */ int min=cal(bottom,top),tem=cal(top,bottom); min=min<tem? min:tem; re(bottom); re(top); tem=cal(bottom,top); min=min<tem? min:tem; tem=cal(top,bottom); min=min<tem? min:tem; cout << min << endl; } return 0; } |
题目来源:算法竞赛入门经典(第2版) 刘汝佳
解决两个长条放入高度为3的容器中,寻找最短容器长度的问题。通过数组操作实现不同排列组合,确保能容纳两个长条。
426

被折叠的 条评论
为什么被折叠?



