《算法竞赛入门经典》 习题3-11 换抵挡装置(Kickdown,ACM/ICPC NEERC 2006,UVa1588)

《算法竞赛入门经典》 习题3-11 换低挡装置(Kickdown,ACM/ICPC NEERC 2006,UVa1588)

原题:

A research laboratory of a world-leading automobile company has received an order to create a special transmission mechanism, which allows for incredibly efficient kickdown — an operation of switching to lower gear. After several months of research engineers found that the most efficient solution requires special gears with teeth and cavities placed non-uniformly. They calculated the optimal flanks of the gears. Now they want to perform some experiments to prove their findings.
The first phase of the experiment is done with planar toothed sections, not round-shaped gears. A section of length n consists of n units. The unit is either a cavity of height h or a tooth of height 2h. Two sections are required for the experiment: one to emulate master gear (with teeth at the bottom) and one for the driven gear (with teeth at the top).
《算法竞赛入门经典》 习题3-11 换抵挡装置(Kickdown,ACM/ICPC NEERC 2006,UVa1588)
There is a long stripe of width 3h in the laboratory and its length is enough for cutting two engaged sections together. The sections are irregular but they may still be put together if shifted along each other.
《算法竞赛入门经典》 习题3-11 换抵挡装置(Kickdown,ACM/ICPC NEERC 2006,UVa1588)
The stripe is made of an expensive alloy, so the engineers want to use as little of it as possible. You need to find the minimal length of the stripe which is enough for cutting both sections simultaneously.
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>

#define maxn 100
int main(){
	freopen("input.txt","r",stdin);
	char ch;
	int lm,ld;
	while(scanf("%c",&ch)==1&&ch!='\n'){	//循环读入若干组数据
		int m[maxn]={0},d[maxn]={0};	//m存放主串,d存放字串
		lm=0,ld=0;
		m[lm++]=ch-'0';	//字符转化为数字
		while(scanf("%c",&ch)==1&&ch!='\n'){	
			m[lm++]=ch-'0';
		}
		while(scanf("%c",&ch)==1&&ch!='\n'){
			d[ld++]=ch-'0';
		}
		int i=0,j=0;
		while(j<ld){	//这里采用类似于暴力模式匹配的方法
			if(m[i]+d[j]<=3){	//相匹配
				i++;
				j++;
			}
			else{	//失配
				i=i-(j-1);	//i回溯
				j=0;	//j从头开始
			}
		}
		if(i<lm)	//最短长度为主串长度
			printf("%d\n",lm);
		else	
			printf("%d\n",i);
	}
	return 0;
} 

感觉我的输入写的太复杂了写 qaq