Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 7067 | Accepted: 2626 |
Description
Bessie has moved to a small farm and sometimes enjoys returning to visit one of her best friends. She does not want to get to her old home too quickly, because she likes the scenery along the way. She has decided to take the second-shortest rather than the shortest path. She knows there must be some second-shortest path.
The countryside consists of R (1 ≤ R ≤ 100,000) bidirectional roads, each linking two of the N (1 ≤ N ≤ 5000) intersections, conveniently numbered 1..N. Bessie starts at intersection 1, and her friend (the destination) is at intersection N.
The second-shortest path may share roads with any of the shortest paths, and it may backtrack i.e., use the same road or intersection more than once. The second-shortest path is the shortest path whose length is longer than the shortest path(s) (i.e., if two or more shortest paths exist, the second-shortest path is the one whose length is longer than those but no longer than any other path).
Input
Lines 2.. R+1: Each line contains three space-separated integers: A, B, and D that describe a road that connects intersections A and B and has length D (1 ≤ D ≤ 5000)
Output
Sample Input
4 4 1 2 100 2 4 200 2 3 250 3 4 100
Sample Output
450
题意及分析:
有n个点,R条路,路是双向。想要从1出发到达n,路径要求为次短路径。
具体的思路参考了别人:http://blog.youkuaiyun.com/kongming_acm/article/details/5741890
高手是这样写的:
求次短路需要深刻理解Dijkstra的定标技术, 思想就是每次都将某个状态的标记(即长度)永久固定, 普通的Dijkstra的状态是一维的, 即顶点编号占一维, 每次确定一个顶点编号下的最短路. 现在将状态扩展到二维, 第一维仍然是顶点编号, 第二维的长度只有2, 用于分别记录最短路和次短路, 直观点说就是开一个二维数组, 第一维是顶点数, 第二维0号位置放最短路, 1号位置放次短路
我觉得你要是比较了解普通的Dijkstra就能大致理解这个了。我觉得具体细节最好自己弄一个相对简单的图,手动走一下,这样理解也好一点。
AC代码:
#include
#include
#include
#define INF 0x3f3f3f3f
#define N 5010
using namespace std;
struct edge
{
int st,ed;
int val,next;
}a[200010];
int m,n,visited[N][2],dis[N][2],head[N];
void Dijkstra()
{
int i,j,pos,k;
memset(visited,0,sizeof(visited));
memset(dis,0x3f,sizeof(dis));
dis[1][0]=0;
for(i=1;i<=2*n;i++)
{
int mi=INF;
for(j=1;j<=n;j++)
{
if(!visited[j][0]&&dis[j][0]
mi+w)
{
dis[t][1]=dis[t][0];
dis[t][0]=mi+w;
}
else if(dis[t][0]==mi+w)
continue;
else if(dis[t][1]>=mi+w)
{
dis[t][1]=mi+w;
}
}
}
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
int i;
memset(head,-1,sizeof(head));
for(i=1;i<=2*m;i++) //注意是双向边
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
a[i].st=x;a[i].ed=y;a[i].val=z;
a[i].next=head[x];head[x]=i;
a[++i].st=y;a[i].ed=x;a[i].val=z;
a[i].next=head[y];head[y]=i;
}
Dijkstra();
printf("%d\n",dis[n][1]);
}
}