题目链接:https://cn.vjudge.net/contest/276233#problem/B
思路和上一个一样,不过注意点有两个,第一,对dis数组进行初始化的时候,应该初始化成ox3f3f3f3f3f3f3f,因为这个题目的边权加到一定程度的时候会超过int。第二点,如果是memset,好像不能对dis数组初始化0x3f3f3f3f3f3f3f,然后我用for循环初始化的,就过了。。。
AC代码:
#include<iostream>
#include<cstring>
#include<stack>
#include<iomanip>
#include<cmath>
#include<queue>
#include<algorithm>
#include<stdio.h>
using namespace std;
# define ll long long
# define inf 0x3f3f3f3f3f3f3f
const int maxn = 1000+100;
const int maxedge= 2000000+10;
int n,ml,md;
int num,head[maxn];
ll dis[maxn];
int out[maxn],vis[maxn];
struct node
{
int to;
ll cost;
int nex;
} edge[maxedge];
void init()
{
num=0;
for(int i=0;i<=n;i++){
dis[i]=inf;
head[i]=-1;
vis[i]=0;
out[i]=0;
}
}
void addedge(int fr,int to,ll cost)
{
edge[num].to=to;
edge[num].cost=cost;
edge[num].nex=head[fr];
head[fr]=num++;
}
ll spfa()
{
queue<int>q;
q.push(1);
dis[1]=0;
vis[1]=1;
out[1]++;
while(!q.empty())
{
int tmp=q.front();
out[tmp]++;
if(out[tmp]>n)
return -1;
q.pop();
vis[tmp]=0;
for(int i=head[tmp]; i!=-1; i=edge[i].nex)
{
int u=edge[i].to;
if(dis[u]>dis[tmp]+edge[i].cost)
{
dis[u]=dis[tmp]+edge[i].cost;
if(vis[u])
continue;
q.push(u);
vis[u]=1;
}
}
}
if(dis[n]==inf)
return -2;
return dis[n];
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int u,v;
ll w;
scanf("%d %d %d",&n,&ml,&md);
init();
for(int i=1; i<=ml; i++)
{
scanf("%d %d %lld",&u,&v,&w);
addedge(u,v,w);
}
for(int i=1; i<=md; i++)
{
scanf("%d %d %lld",&u,&v,&w);
addedge(v,u,-w);
}
ll ans=spfa();
printf("%lld\n",ans);
}
return 0;
}