洛谷 P1359 租用游艇(Floyd, Dijkstra,SPFA)

https://www.luogu.com.cn/problem/P1359

代码

Floyd

#include 
using namespace std;
const int N = 202;

int n;
int dis[N][N];

int main() {
	cin >> n;
	for (int i = 1; i < n; i++) {
		for (int j = i + 1; j <= n; j++) {
			int t; cin >> t;
			dis[i][j] = t;
		}
	}
	for (int k = 1; k <= n; k++) {
		for (int i = 1; i <= n; i++) {
			for (int j = i + 1; j <= n; j++) {
				if (k <= i) continue;
				if (dis[i][k] + dis[k][j] < dis[i][j])
					dis[i][j] = dis[i][k] + dis[k][j];
			}
		}
	}
	cout << dis[1][n] << endl;
	return 0;
}

Dijkstra

#include 
using namespace std;
const int N = 202;
const int INF = 0x3f3f3f3f;
int n;
int g[N][N];
int dis[N];
int vis[N];

int main() {
	cin >> n;
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= n; j++) {
			g[i][j] = i == j ? 0 : INF;
		}
	for (int i = 1; i < n; i++) {
		for (int j = i + 1; j <= n; j++) {
			cin >> g[i][j];
			if (i == 1) dis[j] = g[i][j];
		}
	}
	dis[1] = 0, vis[1] = 1;
	for (int i = 1; i < n; i++) {
		int mindis(INF), k(0);
		for (int j = 1; j <= n; j++) {
			if (vis[j]) continue;
			if (dis[j] < mindis) 
				k = j, mindis = dis[j];
		}
		vis[k] = 1;
		for (int j = 1; j <= n; j++) {
			if (dis[j] > dis[k] + g[k][j])
				dis[j] = dis[k] + g[k][j];
		}
	}
	cout << dis[n] << endl;
	return 0;
}

SPFA

#include 
using namespace std;
const int N = 202;

struct edge {
	int v;
	int w;
};

int n;
vector <edge> g[N];
int dis[N];
int inq[N];
queue <int> q;

int main() {
	cin >> n;
	for (int i = 1; i < n; i++) {
		for (int j = i + 1; j <= n; j++) {
			int t; cin >> t;
			g[i].push_back((edge){j, t});
		}
	}

	memset(dis, 0x3f3f3f3f, sizeof(dis));
	dis[1] = 0;
	q.push(1);
	while (!q.empty()) {
		int fro = q.front();
		q.pop(); 
		inq[fro] = 0;
		for (int i = 0; i < g[fro].size(); i++) {
			edge nv = g[fro][i];
			if (dis[nv.v] > dis[fro] + nv.w) {
				dis[nv.v] = dis[fro] + nv.w;
				if (!inq[nv.v]) {
					q.push(nv.v); inq[fro] = 1;
				}
			}
		}
	}
	cout << dis[n] << endl;
	return 0;
}

你可能感兴趣的:(随笔,code,图论)