dijkstra算法模板:
Int visited[i]//结点i若被访问则为1,没有则为0 Int dist[i]// 目前结点j到其他各结点的最短路的长度 Int w[i][j]//边(i,j)的权值 初始化:(结点1~n) memset(v,0,sizeof(v)); dist[j]=0; dist[i]=inf;(i>=1&&i<=n&&i!=j) cin>>a>>b>>x; if(w[a][b]>x)//a到b可能有多条路径 w[b][a]=w[a][b]=x; w[x][y]=inf;边(x,y)不存在 for(i=1;i<=n;i++) { int x,m=inf; for(j=1;j<=n;j++) if(!visited[j]&&dist[j]<m) { m=dist[j]; x=j; } visited[x]=1; for(j=1;j<=n;j++) If(!visited[j]) dist[j]=min(dist[j],dist[x]+w[x][j]) }
Description
Lode Runner is a famous game, I think you played in your childhood.
Ok, now, I simple the problem. In the game, it has N horizontal roads, the ladders always stay at right side vertically, and the ladders are extending towards up and down with unlimited length. If ladder near or cross a road, little WisKey will walk on the
road by climbed the ladder. Two roads were covered by each other in the X-axis; it will be considered can be passing through. Each road has an integer W means the dangerous level.
Little WisKey must start at No.1 road, and he can’t go back, he always go ahead. WisKey want to go some roads, so he needs to know how minimum sum of dangerous will happen. You can finish the game, yes?
Input
The first integer C represents the number of cases, And C cases followed.
Each test case contains a single integer N roads (1<=N<= 2000) and M destinations (1<=M<=500). The next N line contains three integers Si, Ei, Wi, meaning the road build from Si to Ei, and the Wi dangerous level (0 <= Si <= Ei <= 1000, 1 <= Wi <= 1000). And
the roads sorted by Ei increasing yet. The last M line contains integers mean little WisKey’s destinations.
Output
For each questions, output the minimum sum of dangerous. If can’t reach the goal, please print -1.
Sample Input
3 10 4 1 4 7 5 6 3 3 7 5 2 9 8 10 13 8 12 14 11 11 15 13 16 18 5 17 19 6 8 20 9 1 2 3 10 5 5 1 4 5 3 6 10 5 8 20 2 9 1 7 10 2 1 2 3 4 5 4 4 1 5 1 2 7 20 2 7 3 7 9 4 1 2 3 4
Sample Output
7 -1 12 24 5 15 35 6 8 1 21 4 8
把点的权值转化为通向它的边的权值
#include<iostream> #include<cstring> #include<cstdio> #include<cmath> #include<string> #include<algorithm> #define LL long long #define inf 0x3f3f3f3f using namespace std; struct node { int l,r; int w; }q[2010]; bool visited[2010]; int dist[2010]; int wx[2010][2010]; int main() { int T; cin>>T; while(T--) { int n,m; cin>>n>>m; for(int i=1;i<=n;i++) scanf("%d%d%d",&q[i].l,&q[i].r,&q[i].w); memset(wx,inf,sizeof(wx)); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) if(i==j) wx[i][j]=wx[j][i]=0; for(int i=2;i<=n;i++) for(int j=1;j<=i-1;j++) if(q[j].r>=q[i].l) wx[j][i]=q[i].w; memset(visited,0,sizeof(visited)); memset(dist,inf,sizeof(dist)); dist[1]=0; for(int i=1;i<=n;i++) { int x,mx=inf; for(int j=1;j<=n;j++) if(!visited[j]&&dist[j]<mx) { mx=dist[j]; x=j; } visited[x]=1; for(int j=1;j<=n;j++) dist[j]=min(dist[j],dist[x]+wx[x][j]); } while(m--) { int b; cin>>b; if(dist[b]==inf) cout<<-1<<endl; else cout<<dist[b]+q[1].w<<endl; } } return 0; }