单源最短路算法模板

2019暑期牛客多校第4场-J .free
题干

Your are given an undirect connected graph.Every edge has a cost to pass.You should choose a path from S to T and you need to pay for all the edges in your path. However, you can choose at most k edges in the graph and change their costs to zero in the beginning. Please answer the minimal total cost you need to pay.
输入描述:
The first line contains five integers n,m,S,T,K.

For each of the following m lines, there are three integers a,b,l, meaning there is an edge that costs l between a and b.

n is the number of nodes and m is the number of edges.
输出描述:
An integer meaning the minimal total cost.
示例1
输入
复制
3 2 1 3 1
1 2 1
2 3 2
输出
复制
1
备注:
1 \le n,m \le 10^3,1 \le S,T,a,b \le n,0 \le k \le m,1 \le l \le 10^61≤n,m≤10
3
,1≤S,T,a,b≤n,0≤k≤m,1≤l≤10
6
.
Multiple edges and self loops are allowed.

思路:

  1. 图用邻接矩阵表示,初始化邻接矩阵,给矩阵每个元素赋上极大值,暂时表示这两个点之间不连通。
  2. 输入图,在初始化后的邻接矩阵上表示出来。每个元素存的值为两个点的距离,极大值为两点之间不连通。
  3. 开3个数组dis[N]、fina[N]、pro[N],dis[N]用来更新每个点与起点的最短距离,fina[N]用来标记已找到最短路的点,pro[N]用来标记最短路中每个点的上一个点。
  4. 跟新dis[N]的值,再把dis[N]扫一遍,找到起点到起点距离最小的点,并在fina[N]上标记该点,表示该点与源点之间的最短路以找到。
  5. 重复第4个操作,直到找到所有点到源点的最短路。
    dijkstra算法模板
#include
#include
#include
#include
using namespace std;
#define ll long long
const int MAXN=1e3+10;
long long map[MAXN][MAXN];
bool cmp(int  a,int b)
{
	return a>b;
}
void dijkstra(int vcot,int ecot,int vhead,int vtail,int _k)
{
   int min=INT_MAX;
   int fina[MAXN];
   int dis[MAXN];
   int pro[MAXN];

   for(int i=1;i<=vcot;i++) //初始化dis[i] 
   {   
        fina[i]=0;
        pro[i]=0;
        dis[i]=map[vhead][i]; 
   }
   int k;
   int p=vhead;
   fina[vhead]=1;
   pro[vhead]=0;
   dis[vhead]=0;
    for(int i=1;i<=vcot;i++)
    {
        min=INT_MAX;        
        for(int j=1;j<=vcot;j++)  //找到当前dis[i]中离源点最近的点     
        {
            if(!fina[j]&&dis[j]l) map[a][b]=l;
        if(map[b][a]==0) map[b][a]=l;
        else if(map[b][a]>l) map[b][a]=l;
        
    }
    dijkstra(n,m,s,t,k);
    
            
    
}

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