hdu 2053 Swith Game

题解:

  简单模拟题,但是该题穷举的话太浪费时间和空间了。由给出的例子,

Consider the second test case: The initial condition : 0 0 0 0 0 … After the first operation : 1 1 1 1 1 … After the second operation : 1 0 1 0 1 … After the third operation : 1 0 0 0 1 … After the fourth operation : 1 0 0 1 1 … After the fifth operation : 1 0 0 1 0 … The later operations cannot change the condition of the fifth lamp any more. So the answer is 0.

 

可以看出第n个开关的变化得看n有多少个因数,因数总个数为奇数则经过变化后第n个开关的状态为开(1),总因数个数为偶数个时,开关状态为关(0)。代码实现如下:

 

#include <stdio.h>
#include <math.h>

int comfact(int n)
{
	int cnt=1, i;
	for (i=1; i<=n/2; i++)
	{
		if (n % i == 0)
			cnt++;
	}
	return cnt;
}

int main()
{
	int CNF[100001] = {0};
	int i, n;
	for (i=1; i<100001; i++)
		CNF[i] = comfact(i);//CNF[i]存放i的总因数个数
	while (scanf("%d", &n) != EOF)
		printf("%d\n", CNF[n]%2);
	return 0;
}


  思路很简单,但就是不能AC,通过观察CNF[]的前100个元素发现,CNF[i^2](i为自然数)为奇数,其它的为偶数,于是重写代码如下:

#include <stdio.h>
#include <math.h>

int main()
{
	int n, i;
	int A[100000] = {0};
	n = (int)sqrt(100000);
	for (i=1; i<=n; i++)
		A[(int)pow(i, 2)] = 1;
	while (scanf("%d", &n) != EOF)
	{
		printf("%d\n", A[n]);
	}
	return 0;
}

 

终于AC了,你知道为什么吗?

。。。 。。。

因为自然数的因数总是成对出现的对于自然数n,如果有个因数a,就必然存在b使得a*b = n,但是自然数的平方必然存在a*b = n,其中a = b,所以就相对于没有a = b的普通自然数,自然数的平方的总因数个数呈奇数个。

 

posted on 2013-01-21 15:07  zm001  阅读(159)  评论(0)    收藏  举报