题解 | #数据分类处理#
数据分类处理
https://www.nowcoder.com/practice/9a763ed59c7243bd8ab706b2da52b7fd
#include <stdio.h>
#include <math.h>
#include <string.h>
struct intarray {
int *ptr;
int size;
};
/* 函數描述:數字包含判斷 */
int DataProcess(int target, int num) {
int i, n, times10, compnum, timesTar,nTar;
// printf("target=%d ",target);
if (target==0) {
nTar=1;
} else {
for (i=0; ;i++) {
times10=(int)pow(10,i);
if ((target%times10)==target) break;
}
nTar=i;
}
timesTar=(int)pow(10, nTar);
// printf("timesTar=%d ",timesTar);
for (i=0; ;i++) {
times10=(int)pow(10, i);
if ((num%times10)==num) {
break;
}
}
n=i;
// if(target==3&&num==3) printf("n=%d ",n);
for (i=0; i<=(n-nTar); i++) {
times10 = (int)pow(10, i);
// printf("\ntimes10=%d\n", times10);
compnum = ( num-(num/(times10*timesTar))*(times10*timesTar) )/times10;
// if(target==3 && num==3) printf("compnum=%d\n",compnum);
if (target==compnum) return 1;
}
return 0;
}
/* 函數描述:序列去重並重排 */
struct intarray Sort(int *input, int size) {
int i,j,k, temp;
static struct intarray p_outp;
p_outp.ptr = input;
for (i=0; i<size-1; i++) {
for (j=i+1; j<size; j++) {
if (*(p_outp.ptr+i)==*(p_outp.ptr+j)) {
for (k=j; k<size; k++) {
if (k==size-1) {
*(p_outp.ptr+k)=-1;
}
else {
*(p_outp.ptr+k)=*(p_outp.ptr+k+1);
}
}
j--;
size--;
}
}
}
for (i=0; i<size-1; i++) {
for (j=0; j<size-1; j++) {
if (*(p_outp.ptr+j)>*(p_outp.ptr+j+1)) {
temp = *(p_outp.ptr+j);
*(p_outp.ptr+j) = *(p_outp.ptr+j+1);
*(p_outp.ptr+j+1) = temp;
}
}
}
p_outp.size = size;
return p_outp;
}
int main() {
/* 數據獲取 */
int n_I, n_R, i,j;
scanf("%d ", &n_I);
int I[n_I];
for (i=0; i<n_I; i++) {
scanf("%d", &I[i]);
}
scanf("%d ", &n_R);
int R[n_R];
for (i=0; i<n_R; i++) {
scanf("%d", &R[i]);
}
/* R[]數據去重同埋重排 */
struct intarray RR;
RR.ptr = R;
RR = Sort(R, n_R);
int R0[RR.size];
for (i=0; i<RR.size; i++) {
R0[i] = *(RR.ptr+i);
}
/* 哈希表處理 */
int hash[RR.size][101], cntR;
// //為什麼這裡創建hash時,如果用100作為行數就OK,而用RR.size來傳參的話會導致最終出現段錯誤、個別測試用例失敗???
// int hash[100][101], cntR;
// memset(hash, 0, sizeof(hash)/sizeof(hash[0][0]));
memset(hash, 0, sizeof(hash));
// memset(hash, 0, RR.size*101*sizeof(int));
// //接上:而如果這裡採用這種按位初始化為0就可以成功???
for (i=0; i<RR.size; i++) {
cntR=0;
for (j=0; j<n_I; j++) {
if (DataProcess(R0[i], I[j])==1) {
cntR++;
hash[i][0] = cntR;
hash[i][cntR] = j;
}
}
}
/* 輸出數據整理 */
int output[100000]={0}, cnt=1, k;
for (i=0; i<RR.size; i++) {
if (hash[i][0]==0) continue;
else {
output[cnt++] = R0[i]; //R中元素
output[cnt++] = hash[i][0];//I中包含該元素的個數
for (k=1; k<hash[i][0]+1; k++) {
output[cnt++] = hash[i][k]; //索引
output[cnt++] = I[hash[i][k]]; //數值
}
}
}
output[0] = (--cnt);
for (i=0; i<cnt+1; i++) {
printf("%d ",output[i]);
}
return 0;
}


