/*
dijkstra
1046MS 16016K
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define SIZE 2005
#define inf 0xfffffff
using namespace std;
int st[SIZE],ed[SIZE],val[SIZE];
int cnt[SIZE][SIZE],lowcost[SIZE];
bool vis[SIZE];
int C,N,M;
void dijkstra()
{
for(int i=1; i<=N; i++)
lowcost[i] = inf;
for(int i=2; i<=N; i++)
lowcost[i] = cnt[1][i];
lowcost[1] = 0;
vis[1] = true;
for(int i=2; i<=N; i++)
{
int Min = inf,k = 0;
for(int j=1; j<=N; j++)
{
if(lowcost[j] < Min && !vis[j])
{
Min = lowcost[j];
k = j;
}
}
vis[k] = true;
for(int j=1; j<=N; j++)
{
if(lowcost[j] > Min + cnt[k][j] && !vis[j])
lowcost[j] = Min + cnt[k][j];
}
}
}
int main()
{
scanf("%d",&C);
while(C--)
{
scanf("%d%d",&N,&M);
for(int i=1; i<=N; i++)
for(int j=1; j<=N; j++)
cnt[i][j] = inf;
for(int i=1; i<=N; i++)
{
vis[i] = false;
scanf("%d%d%d",&st[i],&ed[i],&val[i]);
for(int j=i-1; j>=1; j--)
{
if(st[i] > ed[j] || ed[i] < st[j])
continue;
cnt[j][i] = val[i];
}
}
dijkstra();
while(M--)
{
int des;
scanf("%d",&des);
if(lowcost[des] == inf)
puts("-1");
else
printf("%d\n",lowcost[des]+val[1]);
}
}
return 0;
}
/*
spfa
984MS 16324K
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#define SIZE 2005
#define inf 0xfffffff
using namespace std;
struct node
{
int to,val,next;
}edge[SIZE*SIZE];
int head[SIZE],idx;
int st[SIZE],ed[SIZE],val[SIZE];
int lowcost[SIZE];
bool vis[SIZE];
int C,N,M;
void addNode(int from,int to,int val)
{
edge[idx].to = to;
edge[idx].val = val;
edge[idx].next = head[from];
head[from] = idx ++;
}
void spfa()
{
queue <int> Q;
for(int i=1; i<=N; i++)
lowcost[i] = inf;
lowcost[1] = 0;
Q.push(1);
vis[1] = true;
while(!Q.empty())
{
int cur = Q.front();
Q.pop();
vis[cur] = false;
for(int i=head[cur]; i!=-1; i=edge[i].next)
{
int to = edge[i].to;
if(lowcost[to] > lowcost[cur] + edge[i].val)
{
lowcost[to] = lowcost[cur] + edge[i].val;
if(!vis[to])
{
vis[to] = true;
Q.push(to);
}
}
}
}
}
int main()
{
scanf("%d",&C);
while(C--)
{
scanf("%d%d",&N,&M);
idx = 0;
for(int i=1; i<=N; i++)
{
head[i] = -1;
vis[i] = false;
}
for(int i=1; i<=N; i++)
{
scanf("%d%d%d",&st[i],&ed[i],&val[i]);
for(int j=i-1; j>=1; j--)
{
if(st[i] > ed[j] || ed[i] < st[j])
continue;
addNode(j,i,val[i]);
}
}
spfa();
int des;
while(M--)
{
scanf("%d",&des);
if(lowcost[des] == inf)
puts("-1");
else
printf("%d\n",lowcost[des]+val[1]);
}
}
return 0;
}
HDU 2851 Lode Runner (最短路径)
最新推荐文章于 2021-09-30 14:42:49 发布