和前面那题几乎一模一样。。依然并查集和边排序,只不过这题是求所有路中最小边最大的情况,那就从最大边开始加入,直到起点和终点连通,打印最后加入的边就行
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct RoadStruct
{
int a;
int b;
int weight;
};
static int total;
static char city[200][31];
static int find_city(char *s)
{
int i;
for (i = 0; i < total; i++)
if (strcmp(city[i], s) == 0)
return i;
strcpy(city[total], s);
return total++;
}
struct CityStruct
{
struct CityStruct *parent;
int rank;
};
typedef struct CityStruct *City;
static City make_set()
{
City s = malloc(sizeof(struct CityStruct));
s->parent = s;
s->rank = 1;
return s;
}
static City find_set(City s)
{
if (s->parent != s)
s->parent = find_set(s->parent);
return s->parent;
}
static void link(City s1, City s2)
{
if (s1->rank > s2->rank)
s2->parent = s1;
else
{
s1->parent = s2;
if (s1->rank == s2->rank)
s2->rank++;
}
}
static void union_set(City s1, City s2)
{
link(find_set(s1), find_set(s2));
}
static int cmp(const void *p1, const void *p2)
{
struct RoadStruct *r1 = (struct RoadStruct*) p1;
struct RoadStruct *r2 = (struct RoadStruct*) p2;
return r2->weight - r1->weight;
}
int main()
{
int i, n, r, count = 0;
char s[31], t[31];
struct RoadStruct *roads = malloc(19900 * sizeof(struct RoadStruct));
City *array = malloc(200 * sizeof(City));
while (scanf("%d %d", &n, &r), n && r)
{
printf("Scenario #%d\n", ++count);
getchar();
int weight;
total = 0;
for (i = 0; i < r; i++)
{
scanf("%s %s %d", s, t, &weight);
roads[i].a = find_city(s);
roads[i].b = find_city(t);
roads[i].weight = weight;
}
getchar();
scanf("%s %s", s, t);
int src = find_city(s);
int dst = find_city(t);
array[src] = make_set();
array[dst] = make_set();
qsort(roads, r, sizeof(struct RoadStruct), cmp);
for (i = 0; i < r; i++)
{
int a = roads[i].a;
int b = roads[i].b;
if (array[a] == NULL)
array[a] = make_set();
if (array[b] == NULL)
array[b] = make_set();
City c1 = find_set(array[a]);
City c2 = find_set(array[b]);
if (c1 != c2)
union_set(c1, c2);
if (find_set(array[src]) == find_set(array[dst]))
{
printf("%d tons\n\n", roads[i].weight);
break;
}
}
for (i = 0; i < total; i++)
{
if (array[i] != NULL)
free(array[i]);
array[i] = NULL;
}
}
free(array);
free(roads);
return 0;
}