50101. Component and Parts
難度:3.5/5
Second Try: 3/5 Used Time: 14:101
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "componentPart.h"
#define MAXLENGTH 16
#define MAXCOMPONENT 64
// typedef struct{
// char name[MAXLENGTH];
// int numComponent;
// int componentPartList[MAXCOMPONENT];
// int price;
// }ComponentPart;
int cnt;
ComponentPart* cp;
int vis[1000] = {0};
int cmp(const void* a, const void* b){
return strcmp(((ComponentPart*)a)->name, ((ComponentPart*)b)->name);
}
int get_price(int idx, int n){
if(vis[idx] == 1) return cp[idx].price;
else if(cp[idx].numComponent == 0){
vis[idx] = 1;
return cp[idx].price;
}
int total_price = 0;
for(int i = 0; i < cp[idx].numComponent; i++){
total_price += get_price(cp[idx].componentPartList[i], n);
}
vis[idx] = 1;
cp[idx].price = total_price;
return total_price;
}
void findPrice(int n, ComponentPart list[]){
cp = list;
cnt = n;
for(int i = 0; i < n; i++){
if(vis[i] == 0) get_price(i, n);
}
qsort(list, n, sizeof(ComponentPart), cmp);
for(int i = 0; i < n; i++){
printf("%s %d\n", list[i].name, list[i].price);
}
return;
}