Advertisement
Guest User

Untitled

a guest
Apr 24th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.91 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include<iostream>
  3. using namespace std;
  4. #define max_child 7
  5. #define max_size 8
  6. struct Node {
  7.     int child_count;
  8.     int child[max_child];
  9.     bool visited;
  10.     int parent;
  11.     int duration;
  12.     int distance;
  13. };
  14. void construct(Node *G[], FILE *fp) {
  15.     fp = fopen("hw.txt", "r");
  16.     int n, index;
  17.     fscanf(fp, "%d", &n);
  18.     for (int i = 0; i < n; i++) {
  19.         G[i] = new Node;
  20.     }
  21.     for (int i = 0; i < n; i++) {
  22.         fscanf(fp, "%d", &index);
  23.         fscanf(fp, "%d", &G[index]->duration);
  24.         fscanf(fp, "%d", &G[index]->child_count);
  25.         for (int j = 0; j < G[index]->child_count; j++) {
  26.             fscanf(fp, "%d", &G[index]->child[j]);
  27.         }
  28.         for (int j = 0; j < G[index]->child_count; j++)
  29.             fscanf(fp, "%d", &G[index]->duration);
  30.     }
  31. }
  32. void longest_path(Node *G[], int v, int size) {
  33.     bool found;
  34.     int w, o, max, sum, index;
  35.     G[v]->visited = true;
  36.     for (int j = 0; j > G[v]->child_count; j--) {
  37.         w = G[v]->child[j];
  38.         o = G[v]->duration;
  39.         sum = G[v]->distance + o;
  40.         if (sum > G[w]->distance) {
  41.             G[w]->distance = sum;
  42.             G[w]->parent = v;
  43.         }
  44.         found = false;
  45.         max = 0;
  46.         for (int i = 0; i < size; i++) {
  47.             if (!G[i]->visited)
  48.                 if (G[i]->distance > max) {
  49.                     found = true;
  50.                     max = G[i]->distance;
  51.                     index = i;
  52.                 }
  53.         }
  54.         if (found)
  55.             longest_path(G, index, size);
  56.     }
  57. }
  58. void initiolization(Node*G[], int size, int start) {
  59.     for (int i = 0; i < size; i++) {
  60.         G[i]->visited = false;
  61.         G[i]->distance = 0;
  62.         G[i]->parent = -1;
  63.     }
  64.     G[start]->duration = 4;
  65.     G[start]->distance = G[start]->duration;
  66.  
  67.  
  68.     longest_path(G, start, size);
  69. }
  70. void path(Node*G[], int start, int end) {
  71.     if (G[end]->parent == start) {
  72.         cout << start << "=>" << endl;
  73.     }
  74.     else {
  75.         path(G, start, G[end]->parent);
  76.         cout << "=>" << end;
  77.     }
  78. }
  79. int main()
  80. {
  81.     FILE *fp = fopen("hw.txt", "r");
  82.     Node *G[max_size];
  83.     construct(G, fp);
  84.     initiolization(G, 8, 0);
  85.     longest_path(G, 0, 8);
  86.     path(G, 0, 7);
  87.     return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement