list

#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> PII;

int n,m,s;
list<PII> chang[110000];
bool qd[110000];
int cnt[110000]; 

void dij()
{
	memset(cnt, 0x3f, sizeof cnt);
	cnt[1] = 0;
	priority_queue<PII, vector<PII>, greater<PII>> heap;
	heap.push({0, 1});
	
	while(heap.size())
	{
		auto t = heap.top();
		heap.pop();
		
		int v = t.second;
		if(qd[v]) continue;
		qd[v] = true;
		
		for(auto it = chang[v].begin(); it != chang[v].end(); it++)
		{
			if(cnt[(*it).first] > cnt[v] + (*it).second)
			{
				cnt[(*it).first] = cnt[v] + (*it).second;
				heap.push({cnt[(*it).first], (*it).first});
			}
		}
	}
}

int main()
{
	cin >> n >> m >> s;
	for(int i = 0; i < m; i++)
	{
		int x,y,z;
		scanf("%d%d%d", &x, &y, &z);
		chang[x].push_back({y, z});
	}
	
	dij();
	
	cout << cnt[n] << endl;
	
	return 0;
}

邻接表

#include <bits/stdc++.h>

using namespace std;

typedef pair<int, int> PII;

const int N = 1e6 + 10;

int n, m;
int h[N], w[N], e[N], ne[N], idx;
int dist[N];
bool st[N];

void add(int a, int b, int c)
{
    e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}

int dijkstra()
{
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;
    priority_queue<PII, vector<PII>, greater<PII>> heap; // ??? 
    heap.push({0, 1});

    while (heap.size())
    {
        auto t = heap.top();
        heap.pop();

        int ver = t.second, distance = t.first;

        if (st[ver]) continue;
        st[ver] = true;

        for (int i = h[ver]; i != -1; i = ne[i])
        {
            int j = e[i];
            if (dist[j] > dist[ver] + w[i])
            {
                dist[j] = dist[ver] + w[i];
                heap.push({dist[j], j});
            }
        }
    }

    if (dist[n] == 0x3f3f3f3f) return -1;
    return dist[n];
}

int main()
{
    scanf("%d%d", &n, &m);

    memset(h, -1, sizeof h);
    while (m -- )
    {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        add(a, b, c);
    }

    printf("%d\n", dijkstra());

    return 0;
}

速度对比 image

0 comments

No comments so far...