Day6-T4
Describe:差分约束模板题吧。。。LG上竟然是省选+
code:
#include<bits/stdc++.h>
#define INF 214748364
using namespace std;
int n,ml,md,flg,tot,x,y,z;
int son[10010],nxt[10010],w[10010],fir[1010];
queue<int>q;
inline int read(){
int ret=0,f=1;char ch=getchar();
while (ch<'0'||ch>'9') {if (ch=='-') f=-f;ch=getchar();}
while (ch>='0'&&ch<='9') ret=ret*10+ch-'0',ch=getchar();
return ret*f;
}
inline double read2(){
double X=0,Y=1.0;int w=0;char ch=0;
while(!isdigit(ch)){w|=ch=='-';ch=getchar();}
while(isdigit(ch))X=X*10+(ch^48),ch=getchar();
ch=getchar();
while(isdigit(ch)) X+=(Y/=10)*(ch^48),ch=getchar();
return w?-X:X;
}
inline void write(int x){
if(x<0){putchar('-');write(-x);return;}
if(x/10) write(x/10);
putchar(x%10+'0');
}
void add(int x,int y,int z)
{
w[++tot]=z;
son[tot]=y;
nxt[tot]=fir[x];
fir[x]=tot;
}
int d[1010],cir[1010];
bool vis[1010];
inline void spfa(int k) //SprprFA
{
memset(vis,0,sizeof(vis));
memset(cir,0,sizeof(cir));
for(int i=1;i<=n;i++)d[i]=INF;
d[1]=0,cir[1]=1;q.push(k);
while(!q.empty())
{
int x=q.front();
vis[x]=0;
for(int i=fir[x];i;i=nxt[i])
if(d[son[i]]>d[x]+w[i])
{
d[son[i]]=d[x]+w[i];
if(++cir[son[i]]>=n){write(-1),exit(0);}
if(!vis[son[i]])
{
q.push(son[i]);
vis[son[i]]=1;
}
}
q.pop();
}
}
int main()
{
n=read(),ml=read(),md=read();
for(int i=1;i<=ml;i++)x=read(),y=read(),z=read(),add(x,y,z); //差分:转换成a+b>=C 其中C为常数
for(int i=1;i<=md;i++)x=read(),y=read(),z=-read(),add(y,x,z); //连负权
for(int i=1;i<=n;i++)spfa(i);spfa(1); //判图连通性
if(d[n]==INF)write(-2);
else write(d[n]);
}

浙公网安备 33010602011771号