Skip to code
Skip to analysis

This is a explanation of this problem from USACO's training website. I have converted it to markdown. Please do not just copy code; you will not learn anything; at least type it out and understand so you can do it yourself in the future!

Farmer John has discovered the secret to making the sweetest butter in all of Wisconsin: sugar. By placing a sugar cube out in the pastures, he knows the N (1 <= N <= 500) cows will lick it and thus will produce super-sweet butter which can be marketed at better prices. Of course, he spends the extra money on luxuries for the cows.

FJ is a sly farmer. Like Pavlov of old, he knows he can train the cows to go to a certain pasture when they hear a bell. He intends to put the sugar there and then ring the bell in the middle of the afternoon so that the evening’s milking produces perfect milk.

FJ knows each cow spends her time in a given pasture (not necessarily alone). Given the pasture location of the cows and a description of the paths that connect the pastures, find the pasture in which to place the sugar cube so that the total distance walked by the cows when FJ rings the bell is minimized. FJ knows the fields are connected well enough that some solution is always possible.



Line 1: Three space-separated integers: N, the number of pastures: P (2 <= P <= 800), and the number of connecting paths: C (1 <= C <= 1,450). Cows are uniquely numbered 1..N. Pastures are uniquely numbered 1..P.
Lines 2..N+1: Each line contains a single integer that is the pasture number in which a cow is grazing. Cow i’s pasture is listed on line i+1.
Lines N+2..N+C+1 Each line contains three space-separated integers that describe a single path that connects a pair of pastures and its length. Paths may be traversed in either direction. No pair of pastures is directly connected by more than one path. The first two integers are in the range 1..P; the third integer is in the range (1..225).


3 4 5
1 2 1
1 3 5
2 3 7
2 4 3
3 4 5


This diagram shows the connections geometrically:

P1 @--1--@ C1
    \    |\
     \   | \
      5  7  3
       \ |   \
        \|    \ C3
      C2 @--5--@
        P3    P4


SAMPLE OUTPUT (file butter.out)



Putting the cube in pasture 4 means: cow 1 walks 3 units; cow 2 walks 5 units; cow 3 walks 0 units – a total of 8.






Alex Schwendner

We approach this problem directly, by calculating the distance from each cow to each pasture. Once this is done, we will simply have to sum the distances for each cow to get the total cost of putting the sugar cube at a given pasture. The key to a fast distance calculation is that our graph is quite sparse. Thus, we use Dijkstra with a heap to calculate the distance from a given cow to all pastures. This requires on the order of N*C*log(P), or about 7,000,000, operations.

#include <stdio.h>
#include <string.h>

const int BIG = 1000000000;

const int MAXV = 800;
const int MAXC = 500;
const int MAXE = 1450;

int cows;
int v,e;

int cow_pos[MAXC];
int degree[MAXV];
int con[MAXV][MAXV];
int cost[MAXV][MAXV];

int dist[MAXC][MAXV];

int heapsize;
int heap_id[MAXV];
int heap_val[MAXV];
int heap_lookup[MAXV];

bool validheap(void){
  for(int i = 0; i < heapsize; ++i){
    if(!(0 <= heap_id[i] && heap_id[i] < v)){
    if(heap_lookup[heap_id[i]] != i){

void heap_swap(int i, int j){
  int s;

  s = heap_val[i];
  heap_val[i] = heap_val[j];
  heap_val[j] = s;

  heap_lookup[heap_id[i]] = j;

  heap_lookup[heap_id[j]] = i;

  s = heap_id[i];
  heap_id[i] = heap_id[j];
  heap_id[j] = s;


void heap_up(int i){
  if(i > 0 && heap_val[(i-1) / 2] > heap_val[i]){
    heap_swap(i, (i-1)/2);

void heap_down(int i){
  int a = 2*i+1;
  int b = 2*i+2;

  if(b < heapsize){
    if(heap_val[b] < heap_val[a] && heap_val[b] < heap_val[i]){
      heap_swap(i, b);
  if(a < heapsize && heap_val[a] < heap_val[i]){
    heap_swap(i, a);

int main(){

  FILE *filein = fopen("", "r");
  fscanf(filein, "%d %d %d", &cows, &v, &e);
  for(int i = 0; i < cows; ++i){
    fscanf(filein, "%d", &cow_pos[i]);
  for(int i = 0; i < v; ++i){
    degree[i] = 0;
  for(int i = 0; i < e; ++i){
    int a,b,c;
    fscanf(filein, "%d %d %d", &a, &b, &c);

    con[a][degree[a]] = b;
    cost[a][degree[a]] = c;

    con[b][degree[b]] = a;
    cost[b][degree[b]] = c;


  for(int i = 0; i < cows; ++i){
    heapsize = v;
    for(int j = 0; j < v; ++j){
      heap_id[j] = j;
      heap_val[j] = BIG;
      heap_lookup[j] = j;
    heap_val[cow_pos[i]] = 0;

    bool fixed[MAXV];
    memset(fixed, false, v);
    for(int j = 0; j < v; ++j){
      int p = heap_id[0];
      dist[i][p] = heap_val[0];
      fixed[p] = true;
      heap_swap(0, heapsize-1);

      for(int k = 0; k < degree[p]; ++k){
	int q = con[p][k];
	  if(heap_val[heap_lookup[q]] > dist[i][p] + cost[p][k]){
	    heap_val[heap_lookup[q]] = dist[i][p] + cost[p][k];


  int best = BIG;
  for(int i = 0; i < v; ++i){
    int total = 0;
    for(int j = 0; j < cows; ++j){
      total += dist[j][i];
    best <?= total;

  FILE *fileout = fopen("butter.out", "w");
  fprintf(fileout, "%d\n", best);


Back to top