• hdu1874 (spfa 最短路)


    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1874

    很简单的最短路问题,刚刚学习spfa,其实很简单,思想和一维动态规划差不多,数组d[i]表示起点s到i的最短距离,不断用bfs更新这个距离就行,如果终点为t,那么最终d[t]就是起点s到t的最短路。d[i] = min(d[i] ,d[j] + e(i , j) ) ; e(i , j)是 i 点到 j点的边权。

    该题AC代码:

    #include<iostream>
    #include<vector>
    #include<queue>
    #include<algorithm>
    #include<cstring>
    using namespace std;
    struct node{
    	vector<pair<int,int> > vex;
    }g[205];
    int inq[205],d[205];
    int main(){
    	int n,m;
    	while(cin>>n>>m){
    		for(int i = 0;i<205;i++){
    			g[i].vex.clear() ; 
    			inq[i] = 0;
    			d[i] = 1e9;
    		}
    		
    		for(int i = 0;i<m;i++){
    			int a,b,x;
    			cin>>a>>b>>x;
    			g[a].vex.push_back(make_pair(b,x));
    			g[b].vex.push_back(make_pair(a,x));  
    		}
    		queue<int> q;
    		int s,t;
    		cin>>s>>t;
    		q.push(s);
    		d[s] = 0;
    		inq[s] = 1;
    		while(!q.empty() ){
    			int now = q.front();
    			q.pop() ;
    			inq[now] = 0;
    			for(int i = 0;i<g[now].vex.size() ;i++ ){
    				int v = g[now].vex[i].first;
    				if(d[v] > d[now] + g[now].vex[i].second ){
    					d[v] = d[now] + g[now].vex[i].second; 
    					if(inq[v] == 1){
    						continue;
    					}
    					inq[v] == 1;
    					q.push(v);  
    				}
    				 
    			}
    		}
    		if(d[t]==1e9){
    			cout<<-1<<endl;
    		} 
    		else{
    			cout<<d[t]<<endl;
    		}
    	}
    	return 0;
    }
  • 相关阅读:
    第三章 Jenkins参数及web项目
    第二章 Jenkins的详细介绍
    第一章 Git+Gitlab介绍和安装
    第二章 Centos7下Airflow2.1.0安装
    第一章 Airflow基本原理
    第五章 Pinpoint-Apm常见报错
    第四章 Docker方式安装 Pinpoint
    数论练习
    CF练习
    矩阵乘法
  • 原文地址:https://www.cnblogs.com/AaronChang/p/12129646.html
Copyright © 2020-2023  润新知