题解 | #数据分类处理#
数据分类处理
https://www.nowcoder.com/practice/9a763ed59c7243bd8ab706b2da52b7fd
#include <stdio.h> #include <stdlib.h> #include <math.h> //幂函数 返回a的b次幂 int mi(int a,int b) { int res=1; if(b==0) return 1; for (int i=1;i<=b;i++) { res=res*a; } return res; } //判断a里面是否包含b char baohan(int a,int b) { int i=0; int x=10^0; int y=b/x; while(b/mi(10,i)) { x=10^i; y=b/x; i++; } //i表示b的位数 if (b==0) { while(a) { if(a%10) { a=a/10; } else return 1; } return 0; } while(a>=b) { if((a-b)%mi(10,i)) { a=a/10; } else { return 1; } } return 0; } //删除数组data中place编号的元素 void delys(int * data,int cnt ,int place) { for(int i=place;i<cnt-1;i++) { data[i]=data[i+1]; } } //对数组进行排序 并删除重复元素 返回排序后元素个数 int paixu(int* data,int cnt) { int temp=0; for (int i=0;i<cnt-1;i++) { for (int j=i;j<cnt;j++) { if(data[i]>data[j]) { temp=data[i]; data[i]=data[j]; data[j]=temp; } } } int k=0; while(k<cnt-1) { if(data[k]==data[k+1]) { delys(data,cnt,k+1); cnt--; } else k++; } return cnt; } //这里我用了malloc 分配内存 因为没有循环调用所以我就没有手动free。。。 int main() { int datacnt=0; scanf("%d",&datacnt); int* data=(int*) malloc(sizeof(int)*datacnt); for (int i=0;i<datacnt;i++) scanf("%d",data+i); int indexcnt=0; scanf("%d",&indexcnt); int * index=(int*)malloc(sizeof(int)*indexcnt); for (int i=0;i<indexcnt;i++) scanf("%d",index+i); indexcnt= paixu(index,indexcnt); //链表形式储存成员 typedef struct { int place; int neirong; void* next; } chengyuan_struct ; //链表根节点 typedef struct { int index; int searchcnt; chengyuan_struct* firstchengyuan; }root ; int outpucnt=0; root* result =(root* )malloc(sizeof(root)*indexcnt); chengyuan_struct* pointer=NULL; for (int i=0;i<indexcnt;i++) { result[i].index=index[i]; result[i].searchcnt=0; for (int j=0;j<datacnt;j++) { if (baohan(data[j],index[i])) { result[i].searchcnt++; if (result[i].searchcnt==1) { //当前根节点下的第一个成员 result[i].firstchengyuan=(chengyuan_struct *)malloc(sizeof(chengyuan_struct)); pointer=result[i].firstchengyuan; pointer->neirong=data[j]; pointer->place=j; pointer->next=NULL; } else { //非当前根节点下第一个成员 pointer->next=malloc(sizeof(chengyuan_struct)); pointer=(chengyuan_struct *)(pointer->next); pointer->neirong=data[j]; pointer->place=j; pointer->next=NULL; } } } } //统计输出数据个数 for (int i=0;i<indexcnt;i++) { if(result[i].searchcnt) { outpucnt+=2*(result[i].searchcnt+1); } } printf("%d ",outpucnt); //链表遍历输出 for (int i=0;i<indexcnt;i++) { if (result[i].searchcnt) { printf("%d %d ",result[i].index,result[i].searchcnt); pointer=result[i].firstchengyuan; while (pointer!=NULL) { printf("%d %d ",pointer->place,pointer->neirong); pointer=(chengyuan_struct*)(pointer->next); } } } }