97人阅读 评论(0)

# Harry Potter and the Final Battle

Time Limit: 5000/3000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 3267    Accepted Submission(s): 913

Problem Description
The final battle is coming. Now Harry Potter is located at city 1, and Voldemort is located at city n. To make the world peace as soon as possible, Of course, Harry Potter will choose the shortest road between city 1 and city n. But unfortunately, Voldemort is so powerful that he can choose to destroy any one of the existing roads as he wish, but he can only destroy one. Now given the roads between cities, you are to give the shortest time that Harry Potter can reach city n and begin the battle in the worst case.

Input
First line, case number t (t<=20).
Then for each case: an integer n (2<=n<=1000) means the number of city in the magical world, the cities are numbered from 1 to n. Then an integer m means the roads in the magical world, m (0< m <=50000). Following m lines, each line with three integer u, v, w (u != v,1 <=u, v<=n, 1<=w <1000), separated by a single space. It means there is a bidirectional road between u and v with the cost of time w. There may be multiple roads between two cities.

Output
Each case per line: the shortest time to reach city n in the worst case. If it is impossible to reach city n in the worst case, output “-1”.

Sample Input
3
4
4
1 2 5
2 4 10
1 3 3
3 4 8
3
2
1 2 5
2 3 10
2
2
1 2 1
1 2 2

Sample Output
15
-1
2

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
#define N 1010
#define M 50050
#define INF 1<<28
struct Edge
{
int v,next,w;
} edge[M*2];
int n,m,cnt;
int vis[N],d[N];
struct Node
{
int pre,id;
} used[N];
void init()
{
cnt=0;
}
{
edge[cnt].v=v;
edge[cnt].w=w;
}
void djstl(int s,int t)
{
for(int i=1; i<=n; i++)
{
d[i]=INF;
if(!t) used[i].pre=s;
}
{
if(edge[u].w<d[edge[u].v])
{
d[edge[u].v]=edge[u].w;
if(!t) used[edge[u].v].id=u;
};
}
memset(vis,0,sizeof(vis));
vis[s]=1;
for(int i=1; i<=n; i++)
{
int maxn=INF;
int v=-1;
for(int j=1; j<=n; j++)
if(!vis[j]&&maxn>d[j])
{
maxn=d[j];
v=j;
}
if(v==-1) continue;
vis[v]=1;
{
int e=edge[u].v;
if(!vis[e]&&d[v]+edge[u].w<d[e])
{
d[e]=d[v]+edge[u].w;
if(!t) used[e].pre=v,used[e].id=u;
}
}
}
}
int main()
{
int s,t,w;
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d %d",&n,&m);
init();
for(int i=0; i<m; i++)
{
scanf("%d %d %d",&s,&t,&w);
}
djstl(1,0);
int maxn=d[n];
for(int i=n; i!=1; i=used[i].pre)
{
int val=edge[used[i].id].w;
edge[used[i].id].w=INF;
djstl(1,1);
edge[used[i].id].w=val;
maxn=max(maxn,d[n]);
}
if(maxn>=INF) printf("-1\n");
else printf("%d\n",maxn);
}
return 0;
}


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：82664次
• 积分：4635
• 等级：
• 排名：第6318名
• 原创：396篇
• 转载：11篇
• 译文：0篇
• 评论：21条
阅读排行
最新评论