POJ-3268 Dijkstra()单源对短路,小技巧0.0

Dijkstra()单源对短路,小技巧 0.0

POJ-3268来讨论一下吧嘻嘻!!

题干----Silver Cow Party

       One cow from each of N farms (1 ≤ N ≤ 1000) conveniently numbered 1..N is going to attend the big cow party to be held at farm #X (1 ≤ XN). A total of M (1 ≤ M ≤ 100,000) unidirectional (one-way roads connects pairs of farms; road i requires Ti (1 ≤ Ti ≤ 100) units of time to traverse.

       Each cow must walk to the party and, when the party is over, return to her farm. Each cow is lazy and thus picks an optimal route with the shortest time. A cow's return route might be different from her original route to the party since roads are one-way.

       Of all the cows, what is the longest amount of time a cow must spend walking to the party and back?

题意:
       有N头牛,来自n个农场,被编号为1,2,3,4,5,6,7......n;现在这些牛要到X号农场去开party;选择最短的路去X农场,再选择最短的路回家;求所有牛中走的距离中最大的;

Input

       Line 1: Three space-separated integers, respectively: N, M, and X
       Lines 2..M+1: Line i+1 describes road i with three space-separated integers: Ai, Bi, and Ti. The described road runs from farm Ai to farm Bi, requiring Ti time units to traverse.

Output

       Line 1: One integer: the maximum of time any one cow must walk.

Sample Input

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

Sample Output

10

无堆优化Dijkstra AC代码:

  • #include<iostream>
    #include<algorithm>
    using namespace std;
    #define inf 0x3f3f3f3f
    int d[1010][1010];
    int dis[1010];
    bool vis[1010];
    int ans[1010];
    int n, m, x;
    void Dijkstra(int mod)
    {
    	fill(dis, dis + n + 1, inf);
    	fill(vis, vis + n + 1, true);
    	dis[x] = 0;
    	while (true)
    	{
    		int v = -1;
    		for (int i = 1; i <= n; i++)
    			if (vis[i] && (v == -1 || dis[i] < dis[v]))v = i;
    		if (v == -1)break;
    		vis[v] = false;
    		for (int i = 1; i <= n; i++)
    		{
    			if (mod == 0)
    				dis[i] = min(dis[i], dis[v] + d[i][v]);
    			else
    				dis[i] = min(dis[i], dis[v] + d[v][i]);
    		}
    
    	}
    }
    int main()
    {
    	int a, b, t;
    	int Ans = 0;
    	cin >> n >> m >> x;
    	for (int i = 0; i <= n; i++)
    		for (int j = 0; j <= n; j++)
    			if (i == j)	d[i][j] = 0;
    			else d[i][j] = inf;
    	for (int j = 1; j <= m; j++)
    	{
    		scanf("%d%d%d", &a, &b, &t);
    		d[a][b] = t;
    	}
    	Dijkstra(0);
    	for (int i = 1; i <= n; i++)
    		ans[i] = dis[i];
    	Dijkstra(1);
    	for (int i = 1; i <= n; i++)
    		Ans = max(Ans, dis[i] + ans[i]);
    	cout << Ans << endl;
    	return 0;
    }
    

       在使用dijkstra()时,求得的是某一点到其他点的最短距离,但是想要求得其他点到的这一点的距离就不太舒服了,我第一想法是Floyd(),但是时间复杂都太大不适合数据量大的题目。也就是说会Time Limit Exceeded;
       有一个小技巧,你把重点换成起点,把起点换成终点,就可以实现一次性求出”其他点到的这一点的距离“。
       假设party为3,共有5个form,把5->3、4->3、2->3,1->3换成3->1、3->2、3->4、3->5。可以选择改变d[i][j]->d[j][i](make d[i][j]=d[j][i]),也可以这样

就到这里了,诸君加油啊!!

posted @ 2021-03-25 20:01  你看码!!!  阅读(43)  评论(0)    收藏  举报