Cod sursa(job #3156241)

Utilizator razviOKPopan Razvan Calin razviOK Data 10 octombrie 2023 22:59:25
Problema Asmax Scor 30
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.46 kb
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>

typedef struct List{
    unsigned short int node;
    struct List *next;
};
void AddInList(List **head,unsigned short int node){
    if(NULL==(*head)){
        (*head)=(List*)malloc(sizeof(List));
        (*head)->node=node;
        (*head)->next=NULL;

        return;
    }

    List *temp=(List *)malloc(sizeof(List));
    temp->node=node;
    temp->next=(*head);
    (*head)=temp;
}
void DeleteFrontList(List **head){
    if(NULL==(*head))
        return;

    List *temp=(*head);
    (*head)=(*head)->next;
    free(temp);
}
void PrintList(List *head){

    if (NULL==head) return;
    printf("%hu",head->node);
    head=head->next;
    while(NULL!=head){
        printf("--%hu",head->node);
        head=head->next;
    }
}
int Maximum(int a,int b){
    return (a>b) ? a:b;
}
void DFS(unsigned short int Node,int *maxrez,int *MaxSum,List **NeighbList,int *V,bool *visited){

    visited[Node]=true;
    for(List *node=NeighbList[Node];NULL!=node;node=node->next)
       if(false==visited[node->node]){
         DFS(node->node,maxrez,MaxSum,NeighbList,V,visited);
         if(MaxSum[node->node]>=0)
             MaxSum[Node]+=MaxSum[node->node];
    }

   if(MaxSum[Node]==0)
       (*maxrez)=Maximum((*maxrez),V[Node]);
   else (*maxrez)= Maximum((*maxrez), Maximum(V[Node]+ MaxSum[Node],V[Node]));

   if(V[Node]+MaxSum[Node]>0)
       MaxSum[Node]+=V[Node];
 
    //printf("Node:%hu MaxSum:%d maxrez:%d\n",Node,MaxSum[Node],(*maxrez));

}
int main() {

    freopen("asmax.in","r",stdin);
    freopen("asmax.out","w",stdout);

    unsigned short int N,x,y;
    scanf("%hu",&N);

    int *V=(int *) malloc(sizeof(int)*(N+1));
    List **NeighbList=(List **)malloc(sizeof(List*)*(N+1));
    bool *visited=(bool *) malloc(sizeof(bool)*(N+1));
    int *MaxSum=(int *)malloc(sizeof(int)*(N+1));

    for(unsigned int i=1;i<=N;i++) {
        scanf("%d", &V[i]);
        NeighbList[i]=NULL;
        MaxSum[i]=0;
        visited[i]= false;
    }

    /*for(unsigned int i=0;i<N;i++)
        printf("%d ",V[i]);*/
   for(unsigned int i=0;i<N-1;i++){
        scanf("%hu",&x);
        scanf("%hu",&y);
       //printf("%hu %hu\n ",x,y);

       AddInList(&NeighbList[x],y);
       AddInList(&NeighbList[y],x);
    }


    int maxrez=(1<<31);
    DFS(1,&maxrez,MaxSum,NeighbList,V,visited);
   printf("%d",maxrez);
   /*for(unsigned int i=1;i<=N;i++){
       printf("%hu:",i);
       PrintList(NeighbList[i]);
       printf("\n");
   }*/
     free(V);
   return 0;
}