ZOJ-2027

Dijkstra求最短路,说到底还是暴力枚举了每条边免费的情况,不算好算法

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

static char city[100][11];
static int total;
static int map[100][100];

static int find_city(char *s)
{
	int i;
	for (i = 0; i < total; i++)
		if (strcmp(s, city[i]) == 0)
			return i;
	strcpy(city[total], s);
	return total++;
}

static int dijkstra(int from, int to, int freed)
{
	int i, known[100], d[100];
	memset(known, 0, sizeof(known));
	for (i = 0; i < total; i++)
		d[i] = INT_MAX;
	d[from] = 0;
	int now = from, next;
	while (1)
	{
		known[now] = 1;
		int mind = INT_MAX;
		for (i = 0; i < total; i++)
		{
			if (map[now][i] != -1 && !known[i] && map[now][i] <= freed
					&& d[now] + map[now][i] < d[i])
				d[i] = d[now] + map[now][i];
			if (!known[i] && d[i] < mind)
			{
				mind = d[i];
				next = i;
			}
		}
		now = next;
		if (mind == INT_MAX)
			return INT_MAX;
		if (now == to)
			return d[to];
	}
	return INT_MAX;
}

int main()
{
	char src[11], dst[11];
	while (scanf("%s %s", src, dst) != EOF)
	{
		int m, cost, i, j;
		char s[11], t[11];
		scanf("%d", &m);
		getchar();
		total = 0;
		memset(map, -1, sizeof(map));
		while (m--)
		{
			scanf("%s %s %d", s, t, &cost);
			getchar();
			int ss = find_city(s);
			int tt = find_city(t);
			map[ss][tt] = map[tt][ss] = cost;
		}
		int from = find_city(src);
		int to = find_city(dst);
		int res = INT_MAX;
		for (i = 0; i < total; i++)
			for (j = i; j < total; j++)
				if (map[i][j] != -1)
				{
					int temp = map[i][j];
					map[i][j] = map[j][i] = 0;
					int dd = dijkstra(from, to, temp);
					if (dd < res)
						res = dd;
					map[i][j] = map[j][i] = temp;
				}
		printf("%d\n", res);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值