1. 程式人生 > >《演算法競賽入門經典》 習題3-11 換抵擋裝置

《演算法競賽入門經典》 習題3-11 換抵擋裝置

《演算法競賽入門經典》 習題3-11 換抵擋裝置

給出兩個長度分別為n1,n2(n1,n2<=100)且每列高度只為1或2的長條。需要將它們放入一個高度為3的容器,問能夠容納它們的最短容器的長度。
Input
The input file contains several test cases, each of them as described below.
There are two lines in the input, each contains a string to describe a section. The first line describes
master section (teeth at the bottom) and the second line describes driven section (teeth at the top).
Each character in a string represents one section unit — 1 for a cavity and 2 for a tooth. The sections
can not be flipped or rotated.
Each string is non-empty and its length does not exceed 100.
Output


For each test case, write to the output a line containing a single integer number — the minimal length
of the stripe required to cut off given sections.
Sample Input
2112112112
2212112
12121212
21212121
2211221122
21212
Sample Output
10
8
15
(找了原題好理解些)

#include<stdio.h>
#include<string.h>
int main()
{
	char n1[110],n2[110]; 
	char num1[110]={0},num2[110]={0};
	while(scanf("%s%*c",n1)!=EOF) //2表示突出,1表示下凹  
	{
		scanf("%s",n2);
		int len1=strlen(n1);
		int len2=strlen(n2);
		for(int i=0;i<len1;i++) num1[i]=n1[i]-'0'; //把n1,n2轉化為數字 
		for(int i=0;i<len2;i++) num2[i]=n2[i]-'0';
		int i,j;
		for(i=0;i<len1;i++) 
		{
			for(j=0;j<len2;j++)
			{
				if(num1[i+j]+num2[j]>3)
				    break;  //不能嵌入就移動上面的長條,去找下一個可以嵌入的位置 
			}
			if(j==len2)
			    break;  //能成功嵌入 
		}
		int ans1;
		ans1=((i+len2)>len1)?i+len2:len1; //太得全部算進去嘛,就要找一個大的長度 
		for(i=0;i<len2;i++)  /*上下位置交換,如222,2111,由於i是從0開始的,
		                        也就是說移動只能往後移,不能向前移,這個時候,兩個長條上下交換一下*/ 
		{
			for(j=0;j<len1;j++)
			{
				if(num2[i+j]+num1[j]>3)
				    break;  
			}
			if(j==len1)
			    break;  
		}
		int ans2;
		ans2=((i+len1)>len2)?i+len1:len2;   
		printf("%d\n",(ans1<ans2)?ans1:ans2); //輸出小的長度 
	}
	return 0;
}

(誕生日のプレゼントをもらった)