poj 3842 An Industrial Spy

写的代码还挺优的,虽然还是比不上大牛的代码,还是不错的。

刚开始写这道题目的时候一直TLE,我尝试着把能优化的都优化了还用了位运算,终于不TLE了,换成了WA,我心碎了。最后,找错误找了好久,在一次提交之后,终于屏幕上显示Accepted了。

  zhanhb 1632K 79MS GCC 1138B 2011-05-08 16:30:34

 下面贴代码:

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

#define bool char
#define true 1
#define false 0

int ma[312500];
int a[8],c,len;
char str[255];
bool mark[8];

int plist[10000],pcount=0;
bool isprime(int n){
	int i;
	if(n!=2 && !(n%2) || n!=3 && !(n%3) || n!=5 && !(n%5) || n!=7 && !(n%7))
		return false;
	for(i=0;plist[i]*plist[i]<=n;++i){
		if(!(n%plist[i]))return false;
	}
	return n>1;
}
void initprime(){
	int i;
	if(pcount)return;
	for(plist[pcount++]=2,i=3;i<50000;++i){
		if(isprime(i)){
			plist[pcount++]=i;
		}
	}
}
void dfs(int sum){
	int i;
	if(ma[sum/32] & (1<<(sum&31)))return;
	if(isprime(sum))++c;
	ma[sum/32]|=(1<<(sum&31));
	for(i=0;i<len;++i){
		if(!mark[i]){
			mark[i]=true;
			dfs(sum*10+a[i]);
			mark[i]=false;
		}
	}
}
int main(){
	int i,cas;
	initprime();
	scanf("%d",&cas);
	while(cas-- && 1==scanf("%s",str)){
		for(i=0;str[i];++i){
			a[i]=str[i]-'0';
		}
		len=i;
		if(len==1)printf("%d\n",isprime(a[0]));
		else{
			c=0;
			memset(ma,0,sizeof(ma));
			memset(mark,0,sizeof(mark));
			dfs(0);
			printf("%d\n",c);
		}
	}
	return 0;
}



原文地址:https://www.cnblogs.com/zhanhb/p/2040423.html