# This is a simple graph-coloring heuristic that colors # the nodes in the order that AMPL stores them in the data file. set NODES; set EDGES within {NODES, NODES}; data g1.txt; # In the worst case we need to use a different color for each node. set COLORS := {1 .. card(NODES)}; # Data structures to keep track of which nodes have been colored. set COLORED within NODES ordered default {}; set UNCOLORED within NODES ordered default NODES; # The next node to color (i.e., the first node in the # UNCOLORED set. param next_node; # The set of colors allowable for next_node. set POSSIBLE_COLORS ordered; # node_color[i] indicates the color assigned to node i. param node_color {NODES} default 0; # parameters to store the time when the algorithm starts and stops param start_time; param stop_time; # Start the clock. let start_time := _ampl_elapsed_time; repeat { # Select the first node in the uncolored list. let next_node := first(UNCOLORED); # Check the color assignments of next_node's neighbors. let POSSIBLE_COLORS := COLORS; for {u in NODES: (u, next_node) in EDGES or (next_node, u) in EDGES} { let POSSIBLE_COLORS := POSSIBLE_COLORS diff {node_color[u]}; } let node_color[next_node] := first(POSSIBLE_COLORS); let COLORED := COLORED union {next_node}; let UNCOLORED := UNCOLORED diff {next_node}; } until card(UNCOLORED) == 0; let stop_time := _ampl_elapsed_time; # Print out the solution. printf "%d colors were used:\n",card( union {i in NODES}{node_color[i]}); display union {i in NODES} {node_color[i]}; printf "cpu seconds = %f\n",stop_time - start_time; display node_color; printf "\n\nVerification:\n"; for {(i,j) in EDGES} { printf "Edge (%d,%d):\tnode %d gets color %d\tnode %d gets color %d\n",i,j,i,node_color[i],j,node_color[j]; }