FOJ Problem 1091 Zig-Zag Lines

Problem Description

What's the maximum number of regions definable by N zig-zag lines, each of which consists of two parallel infinite half-lines joined by a straight line segment?
Here is an example of 2 zig-zag lines yield 12 regions at the most. 

FOJ Problem 1091 Zig-Zag Lines_第1张图片

Input

The input consists of a sequence of N (<= 10000), which is the number of the zig-zag lines, one per line.

Output

For each N, you should output the number of the maximum regions.

Sample Input

1
2

Sample Output

2
12 


主要是推导,首先要明白一点,向已有的n根线再画一条直线,可以增加n个交点,增加n+1个区域,自己可以动手画画;

从这一点出发,设n对应的区域数为f(n),再求f(n+1)f(n)的关系,得出递推关系这题也就解出来了;

f(n+1)时,前面已经有3*n根线,因为一个‘Z’由两根平行线和一条斜线组成,在画第n+1个‘Z’时,先把‘Z’看成三条直线,即如图

FOJ Problem 1091 Zig-Zag Lines_第2张图片

变化成

FOJ Problem 1091 Zig-Zag Lines_第3张图片

两根平行线与前3*n条线构成3*n个点,所增加的区域是2*(3*n+1)

那根斜线由于前面多了两平行线,所以增加的区域是3*n+2+1=3*n+3

但由于在每个顶点处多算了两区域,如图所示,则在‘Z’的两个顶点要减去4

f(n+1)=f(n)+2*(3*n+1)+3*n+3-4=f(n)+9*n-1;

f(n+1)=f(n)+9*n-1;

通过推导即f(n)=1+n*(9*n-7)/2;


# include "stdio.h" 
int main()
{
	int n, i;
	int sum;
	while(scanf("%d", &n)!=EOF)
	{
		printf("%d\n", 1+n*(9*n-7)/2);
	}
	return 0;
}




你可能感兴趣的:(算法,it,ACM,OJ)