97 lines
2.0 KiB
C
97 lines
2.0 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <stdbool.h>
|
|
|
|
typedef struct Edge {
|
|
int to;
|
|
int weight;
|
|
struct Edge* next;
|
|
} edge;
|
|
|
|
typedef struct {
|
|
int now;
|
|
int distance;
|
|
} tuple;
|
|
|
|
void add_edge(edge** graph, int u, int v, int w);
|
|
tuple find_maxLength_node(int start, edge** graph, int v);
|
|
|
|
int main() {
|
|
int V;
|
|
scanf("%d",&V);
|
|
|
|
edge** graph = (edge**)malloc(sizeof(edge*)*(V+1));
|
|
|
|
for(int i=0; i<V; i++) {
|
|
int u;
|
|
scanf("%d",&u);
|
|
graph[u] = NULL;
|
|
|
|
while(1) {
|
|
int v;
|
|
scanf("%d",&v);
|
|
if(v==-1) break;
|
|
|
|
int w;
|
|
scanf("%d",&w);
|
|
|
|
add_edge(graph,u,v,w);
|
|
}
|
|
}
|
|
|
|
int start = find_maxLength_node(1, graph, V).now;
|
|
int radius = find_maxLength_node(start, graph, V).distance;
|
|
printf("%d\n",radius);
|
|
|
|
|
|
|
|
for(int i = 1; i <= V; i++) {
|
|
edge* ptr = graph[i];
|
|
while(ptr != NULL) {
|
|
edge* temp = ptr;
|
|
ptr = ptr->next;
|
|
free(temp);
|
|
}
|
|
}
|
|
|
|
free(graph);
|
|
return 0;
|
|
}
|
|
|
|
void add_edge(edge** graph, int u, int v, int w) {
|
|
edge* new_edge = (edge*)malloc(sizeof(edge));
|
|
new_edge -> to = v;
|
|
new_edge -> weight = w;
|
|
new_edge -> next = graph[u];
|
|
graph[u] = new_edge;
|
|
}
|
|
|
|
tuple find_maxLength_node(int start, edge** graph, int v) {
|
|
tuple result = {start, 0};
|
|
bool* visited = (bool*)calloc(v+1,sizeof(bool));
|
|
tuple* stack = (tuple*)malloc(sizeof(tuple)*v);
|
|
int top = -1;
|
|
|
|
stack[++top] = result;
|
|
visited[start] = true;
|
|
|
|
while(top != -1) {
|
|
tuple current = stack[top--];
|
|
|
|
if(result.distance < current.distance) result = current;
|
|
|
|
edge* ptr = graph[current.now];
|
|
while(ptr != NULL) {
|
|
if(!visited[ptr->to]) {
|
|
tuple next = {ptr->to, ptr->weight + current.distance};
|
|
stack[++top] = next;
|
|
visited[ptr->to] = true;
|
|
}
|
|
ptr = ptr -> next;
|
|
}
|
|
}
|
|
|
|
free(visited);
|
|
free(stack);
|
|
return result;
|
|
} |