您的位置:首页 > 其它

POJ-1797(最短路的变形)

2014-06-17 21:16 267 查看
容易想到这个式子:pathWeigth[1] = max(pathWeight[1], min(pathWeight[k], weight[1][k]));

类似最短路径的dijsktra算法,我们可以先找到到终点路线可以承载重量最大的节点,再对其相邻节点到终点路线可以承载的重量进行松弛



#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
#define MAX_WEIGHT  1000000

struct Edge{
int to;
int weight;
Edge(int t, int w):to(t), weight(w){}
};
int N, M;
vector<Edge> vertex[1001];
int  pathWeight[1001];
bool inq[1001];

int dijsktra()
{
//initialize
memset(inq + 1, false, N);
for(int i = 1; i < N; ++i) pathWeight[i] = 0;
pathWeight
= MAX_WEIGHT;
//main process
for(int done = 0; done < N; ++done){
//find the vertex which is not in q and has pathWeight to dest
int index = -1, weight = -1;
for(int i = 1; i <= N; ++i){
if(inq[i]) continue;
if(pathWeight[i] > weight){
index = i;
weight = pathWeight[i];
}
}
if(index == 1) break;
inq[index] = true;
//relax those has path to 'index'
for(int i = 0, n = vertex[index].size(); i < n; ++i){
int node = vertex[index][i].to;
pathWeight[node] = max(pathWeight[node],
min(vertex[index][i].weight, weight)
);
}
}
return pathWeight[1];
}

int main()
{
int t, test;
int f, to, w;
for(scanf("%d", &test), t = 1; t <= test; ++t){
scanf("%d%d", &N, &M);
for(int i = 1; i <= N; ++i) vertex[i].clear();
for(int i = 0; i < M; ++i){
scanf("%d%d%d", &f, &to, &w);
vertex[f].push_back(Edge(to, w));
vertex[to].push_back(Edge(f, w));
}
printf("Scenario #%d:\n%d\n\n", t, dijsktra());
}
return 0;
}

顺便复习一下SPFA:



#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
#define MAX_WEIGHT  1000000

struct Edge{
int to;
int weight;
Edge(int t, int w):to(t), weight(w){}
};
int N, M;
vector<Edge> vertex[1001];
int  pathWeight[1001];
bool inq[1001];

int spfa()
{
//initialize
for(int i = 1; i < N; ++i) pathWeight[i] = 0;
pathWeight
= MAX_WEIGHT;
memset(inq + 1, false, N);
//main process
queue<int> q;
q.push(N);
inq
= true;
while(!q.empty()){
int index = q.front(), weight = pathWeight[index];
const vector<Edge>& v = vertex[index];
for(int i = 0, n = v.size(); i < n; ++i){
int node = v[i].to, relax = min(v[i].weight, weight);
if(pathWeight[node] < relax){
pathWeight[node] = relax;
if(!inq[node]){
q.push(node);
inq[node] = true;
}
}
}
q.pop();
inq[index] = false;
}
return pathWeight[1];
}

int main()
{
int t, test;
int f, to, w;
for(scanf("%d", &test), t = 1; t <= test; ++t){
scanf("%d%d", &N, &M);
for(int i = 1; i <= N; ++i) vertex[i].clear();
for(int i = 0; i < M; ++i){
scanf("%d%d%d", &f, &to, &w);
vertex[f].push_back(Edge(to, w));
vertex[to].push_back(Edge(f, w));
}
printf("Scenario #%d:\n%d\n\n", t, spfa());
}
return 0;
}
可以看到SPFA并没有比Dijsktra快多少,估计数据中包含一些稠密图
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: