pangfengliu / programmingtasks

programming tasks from my courses
67 stars 17 forks source link

Component and Parts #353

Open littlehug opened 6 years ago

littlehug commented 6 years ago

Write a function to find the price of components and parts.

Task Description

You are given a set of N components and parts. The difference between a component and a part is that a component consists of other components and parts, and a part is simply a part. Note that the definition of component is recursive, i.e., we use component to define component. However, eventually every component consists of only parts. Now we will be given the price of parts, and we want to compute the price of every component, which is simply the sum of prices of all its parts. Write a function to calculate the price of components, and print the unit price of all components and parts.

Here are examples of parts and components.

part CPU memory power device network
price 1500 383 463 833 200
component components price
PC 1 CPU, 1 memory, 1 power, 1 device 3179
ClusterSystem 4 PC, 1 network 12916

We define component/part as follow. All parts and component are stored in a array and have indice from 0 to N-1. Note that the components and part are mixed in this array. If a ComponentPart has numComponent set to 0, then it is a part, otherwise it is a component, and the indices of its components and parts are stored in the componentPartList array.

typedef struct{
    char name[MAXLENGTH];
    int numComponent;
    int componentPartList[MAXCOMPONENT];
    int price;
}ComponentPart;

The prototype of the function you need to implement is as follows:

void findPrice(int N, ComponentPart list[]);

And you may use the following main function to test your function.

#include<stdio.h>
#include"componentPart.h"
int main(){
    int N;
    scanf("%d",&N);
    ComponentPart list[N];
    for(int i=0;i<N;i++){
        scanf("%s%d",list[i].name,&list[i].numComponent);
        if(list[i].numComponent){
            for(int j=0;j<list[i].numComponent;j++)
                scanf("%d",&list[i].componentPartList[j]);
            list[i].price=0;
        }
        else
            scanf("%d",&list[i].price);
    }
    findPrice(N,list);
    return 0;
}

The componentPart.h is as follow:

#ifndef _COMPONENTPART_H
#define _COMPONENTPART_H
#define MAXLENGTH 16
#define MAXCOMPONENT 64
typedef struct{
    char name[MAXLENGTH];
    int numComponent;
    int componentPartList[MAXCOMPONENT];
    int price;
}ComponentPart;
void findPrice(int N,ComponentPart list[]);
#endif

Subtask