As an emergency rescue team leader of a city, you are given a special map of your country. The map shows several scattered cities connected by some roads. Amount of rescue teams in each city and the length of each road between any pair of cities are marked on the map. When there is an emergency call to you from some other city, your job is to lead your men to the place as quickly as possible, and at the mean time, call up as many hands on the way as possible.
Input
Each input file contains one test case. For each test case, the first line contains 4 positive integers: N (<= 500) - the number of cities (and the cities are numbered from 0 to N-1), M - the number of roads, C1 and C2 - the cities that you are currently in and that you must save, respectively. The next line contains N integers, where the i-th integer is the number of rescue teams in the i-th city. Then M lines follow, each describes a road with three integers c1, c2 and L, which are the pair of cities connected by a road and the length of that road, respectively. It is guaranteed that there exists at least one path from C1 to C2.
Output
For each test case, print in one line two numbers: the number of different shortest paths between C1 and C2, and the maximum amount of rescue teams you can possibly gather.
All the numbers in a line must be separated by exactly one space, and there is no extra space allowed at the end of a line.
Sample Input
5 6 0 2
1 2 1 5 3
0 1 1
0 2 2
0 3 1
1 2 1
2 4 1
3 4 1
Sample Output
2 4
这题蛮有意思的,就是一个最短路的变式,如何更新最短路的个数是个很有意思的事情,这题是受之前做的一道状压dp的题目的启发,做的还算比较顺利。
#include<iostream>
#include<cstdio>
#include<map>
#include<vector>
#include<algorithm>
#include<queue>
#include<cstring>
#define maxx 0x3f3f3f3f
using namespace std;
int n,m,c1,c2;
struct node
{
int to;
int w;
node(int _to,int _w):to(_to),w(_w){}
};
vector<node> graph[505];
int dis[505];
int num[505];
int sum[505];
void addEdge(int x,int y,int w)
{
graph[x].push_back(node(y,w));
graph[y].push_back(node(x,w));
}
int val[505];
bool inQ[505];
void spfa()
{
memset(dis,maxx,sizeof(dis));
queue<int> que;
dis[c2]=0;
num[c2]=1;
sum[c2]=val[c2];
inQ[c2]=true;
que.push(c2);
while(!que.empty())
{
int now=que.front();
inQ[now]=false;
que.pop();
for(int i=0;i<graph[now].size();i++)
{
int v=graph[now][i].to;
if(dis[v]>dis[now]+graph[now][i].w)
{
dis[v]=dis[now]+graph[now][i].w;
num[v]=num[now];
sum[v]=sum[now]+val[v];
if(!inQ[v])
{
que.push(v);
inQ[v]=true;
}
}
else
if(dis[v]==dis[now]+graph[now][i].w)//如果相等的话,路径的数量需要更新
{
num[v]+=num[now];
sum[v]=max(sum[v],sum[now]+val[v]);
if(!inQ[v])
{
que.push(v);
inQ[v]=true;
}
}
}
}
}
int main()
{
scanf("%d%d%d%d",&n,&m,&c1,&c2);
for(int i=0;i<n;i++)
scanf("%d",val+i);
int x,y,w;
while(m--)
{
scanf("%d%d%d",&x,&y,&w);
addEdge(x,y,w);
}
spfa();
printf("%d %d\n",num[c1],sum[c1]);
return 0;
}

本文介绍了一种基于最短路径算法的变种问题解决方法,重点在于如何更新最短路径的数量,通过SPFA算法实现了从起点到终点的最短路径寻找及沿途资源的最大化收集。
816

被折叠的 条评论
为什么被折叠?



