PAT-甲級-1009-Product of Polynomials

Practice 1009

PAT甲級1009

My Solution

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

int main() {
	int K1, K2;
	float* arr1;
	float* arr2;
	
	scanf("%d", &K1);
	arr1 = (float*) malloc(2*K1*sizeof(float));
	for(int i=0; i<2*K1; i++) {
		scanf("%f", &arr1[i]);
	}
	
	scanf("%d", &K2);
	arr2 = (float*) malloc(2*K2*sizeof(float));
	for(int i=0; i<2*K2; i++) {
		scanf("%f", &arr2[i]);
	}
	
	int num = K1 * K2;
	float* temp = (float*) malloc(2*num*sizeof(float)); //別忘了乘2 ,調試的時候會顯示temp[7]數值,實際已經越界 
	
	float exp=0, coef=0;
	int count=0;
	for(int i=0; i<K2; i++) {
		for(int j=0; j<K1; j++) {
			exp = arr2[i*2] + arr1[j*2];
			coef = arr2[i*2+1] * arr1[j*2+1];
			temp[count*2] = exp;
			temp[count*2+1] = coef;
			count++;
		}
	}
	
	float* res = (float*) malloc((2*num+1)*sizeof(float));
	for(int i=0; i<2*num+1; i++) {
		res[i] = 0;
	}
	int* flag = (int*) malloc(num*sizeof(int));
	for(int i=0; i<num; i++) {
		flag[i] = 0;
	}
	
	count=0;
	res[0] = count;
	
	float judge;
	//注意:有多個相等指數的情況 
	//需要注意加到最後一次judge=0 ,中間過程無需判斷judge是否爲0 
	for(int i=0; i<num; i++) {	
		if(flag[i] == 0) {
			res[count*2+1] = temp[i*2];
			res[count*2+2] = judge = temp[i*2+1]; //此時需要設置judge的值 
			for(int j=i+1; j<num; j++) {
				if(temp[i*2] == temp[j*2]) {
					judge = res[count*2+2] + temp[j*2+1];
					res[count*2+2] = judge;
					flag[j] = 1;
				}
			}
			if(judge != 0) {
				count++;
				res[0] = count;
			}
		}
	}
	
	//最後需要排序,冒泡即可
	float temp1, temp2;
	for(int i=0; i<count-1; i++) {
		for(int j=count; j>i+1; j--) {  //原錯誤:j>count-i-1,導致測試點4失敗    更正:j>i+1 
			if(res[2*j-1] > res[2*(j-1)-1]) {
				temp1 = res[2*j-1];
				temp2 = res[2*j];
				res[2*j-1] = res[2*(j-1)-1];
				res[2*j] = res[2*(j-1)];
				res[2*(j-1)-1] = temp1;
				res[2*(j-1)] = temp2;
			}
		}
	} 
	 
	
	for(int i=0; i<count*2+1; i++) {
		if(i==0) printf("%d", (int)res[i]);
		else if(i%2 == 1) printf(" %d", (int)res[i]);
		else printf(" %0.1f", res[i]);
	}
	
	return 0;
}

Test Result

PAT甲級1009
Any idea or discussion is highly welcomed.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章