现在的位置: 首页 > 综合 > 正文

poj1472 模拟计算复杂度

2013年08月10日 ⁄ 综合 ⁄ 共 1831字 ⁄ 字号 评论关闭

        题不难,但是很恶心。输出格式也很极品,尤其我还犯了个不起眼的错,找了好久。就是写出了下面非常捉急的两行代码:

int *coff=(int*)malloc(11*sizeof(int));
memset(coff,0,sizeof(coff));

发现程序时对时错,通过各种打印语句........发现错在memset这行,但是还是没发现有啥不对。上了趟厕所才想起来这地方不是静态数组了,以前初始化数组写习惯了,真是智商捉急啊........改成这样就好了:

int *coff=(int*)malloc(11*sizeof(int));
memset(coff,0,11*sizeof(int));

        代码写的很不美观,懒得改了,也没大有改的动力....

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

void multiply(char* str,int* coff){
	int i;
	if(str[0]=='n'){//乘n实际就是移位,如把n^2的系数移到n^3
		for(i=10;i>0;i--){
			coff[i]=coff[i-1];
		}
		coff[0]=0;
	}else{//乘数字
		int num=atoi(str);
		for(i=0;i<11;i++){
			coff[i]*=num;
		}
	}
}

int read_op(){//普通操作的代价,肯定是常数
	char str[60];
	scanf("%s",str);
	return atoi(str);
}

int* read_loop(){//循环操作
	int *coff=(int*)malloc(11*sizeof(int));
	memset(coff,0,11*sizeof(int));
	
	char looptime[60];
	scanf("%s",looptime);
	
	int i;
	char str[60];
	while(1){
		scanf("%s",str);
		if(str[0]=='O'){
			coff[0]+=read_op();
		}else if(str[0]=='L'){
			int* temp=read_loop();
			for(i=0;i<11;i++){
				coff[i]+=temp[i];
			}
			free(temp);
		}else{
			multiply(looptime,coff);
			return coff;
		}
	}
}

int* read_statement(){
	int *coff=(int*)malloc(11*sizeof(int));
	int i;	
	memset(coff,0,11*sizeof(int));
	
	char str[60];
	while(1){
		scanf("%s",str);
		if(str[0]=='O'){
			coff[0]+=read_op();
		}else if(str[0]=='L'){
			int* temp=read_loop();
			
			for(i=0;i<11;i++){
				coff[i]+=temp[i];
			}
			free(temp);
		}else{
			return coff;
		}
	}
	return coff;
}

void print_result(int* coff){
	printf("Runtime = ");
	int i;
	int head=1;
	for(i=10;i>=0;i--){
		if(coff[i]==0){
			continue;
		}
		if(!head){
			printf("+");
		}else{
			head=0;
		}
		if(coff[i]==1){
			if(i==0){
				printf("1");
			}else if(i==1){
				printf("n");
			}else{
				printf("n^%d",i);
			}
		}else{
			if(i==0){
				printf("%d",coff[i]);
			}else if(i==1){
				printf("%d*n",coff[i]);
			}else{
				printf("%d*n^%d",coff[i],i);
			}
		}
	}
	if(head){
		printf("0");
	}
	printf("\n");
}

int main(void){
	int N;
	int i;
	char str[60];
	scanf("%d",&N);
	for(i=1;i<=N;i++){
		printf("Program #%d\n",i);
		scanf("%s",str);
		int* coff=read_statement();
		print_result(coff);
		free(coff);
		printf("\n");
	}
	return 0;
}

抱歉!评论已关闭.