Til the Cows Come Home-Poj2387(最短路)

Til the Cows Come Home-Poj2387

题目大意:有N个点,给出从a点到b点的距离,当然a和b是互相可以抵达的,问从1到n的最短距离

思路:求最短路模板题,注意本题有重边的情况。

ac代码(bellman-ford):

//#include
#include 
#include 
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = 1e5 + 10;
//邻接表存图
struct Node {
	int u, v, w;
};
std::vector<Node> g;
int dp[MAXN];
int t, n;
//查找s到所有点的最短路;
bool Bellman_ford(int s, int n)
{
	for (int i = 0; i < n; i++) dp[i] = INF;
	dp[s] = 0;
	for (int k = 1; k < n; k++) {
		for (int i = 0; i < g.size(); i++) {
			int u = g[i].u;
			int v = g[i].v;
			int w = g[i].w;
			dp[v] = min(dp[v], dp[u] + w);
		}
	}
	for (int i = 0; i < g.size(); i++) {//判断是否有负环,本题不用;
		int u = g[i].u;
		int v = g[i].v;
		int w = g[i].w;
		if (dp[v] > dp[u] + w) return false;
	}
	return true;
}

int main()
{
	while (cin >> t >> n) {
		g.clear();

		for (int i = 0; i < t; i++) {//存图
			int u, v, w;
			cin >> u >> v >> w;
			g.push_back(Node{ u, v, w });
			g.push_back(Node{ v, u, w });
		}
		Bellman_ford(n, n);
		cout << dp[1] << endl;

	}
	return 0;
}

ac代码(dijkstar):

//#include
#include
using namespace std;
const int INF=0x3f3f3f3f;
const int MAXN=1000+5;
int mp[MAXN][MAXN];
int m,n;
int use[MAXN];
int dis[MAXN];

void dij(int s,int n){
    int pos=-1;
    dis[s]=0;
    for(int i=1;i<=n;i++){
        use[i]=0;
        dis[i]=mp[1][i];
    }
    for(int i=1;i<=n;i++){
        int min1=INF;
        for(int j=1;j<=n;j++){
            if(!use[j]&&dis[j]<min1){
                pos=j;
                min1=dis[j];
            }
        }
        use[pos]=1;
        if(pos==n) break;
        for(int j=1;j<=n;j++){
            if(!use[j]&&dis[j]>mp[pos][j]+dis[pos]){
                dis[j]=mp[pos][j]+dis[pos];
            }
        }
    }
}

int main(){
    cin>>m>>n;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            mp[i][j]=INF;
        }
    }
    for(int i=0;i<m;i++){
        int u,v,w;
        cin>>u>>v>>w;
        if(mp[u][v]>w)
            mp[u][v]=mp[v][u]=w;
    }
    dij(1,n);
    cout<<dis[n]<<endl;
    return 0;
}

学习记录

你可能感兴趣的:(图论)