P4878 [USACO05DEC] Layout G | AcWing1170. 排队布局 | ybt1512:排队布局

//https://www.luogu.com.cn/problem/P4878
//https://www.acwing.com/problem/content/description/1172/
//http://ybt.ssoier.cn:8088/problem_show.php?pid=1512
#include <bits/stdc++.h>
using namespace std;
const int N=1e3+10,M=2*(1e4+10)+2*N;
int q[N];
int Next[M],head[N],to[M],weight[M],cnt;
int h,t;
bool enter[N];
int dist[N],update[N];
int n,m1,m2;
void prepareGraph(){
    cnt=1;
    memset(head,0,sizeof head);
}
void prepareSPFA(){
    h=t=0;
    memset(dist,0x3f,sizeof dist);
    memset(update,0,sizeof update);
    memset(enter,false,sizeof enter);
}
void addEdge(int u,int v,int w){
    Next[cnt]=head[u];
    weight[cnt]=w;
    to[cnt]=v;
    head[u]=cnt++;
}
int spfa(int s){
    update[s]=1;
    enter[s]=true;
    q[t]=s;
    t=(t+1)%N;
    dist[s]=0;
    while(h!=t){
        int u=q[h];
        h=(h+1)%N;
        enter[u]=false;
        for(int ei=head[u],v,w;ei;ei=Next[ei]){
            v=to[ei],w=weight[ei];
            if(dist[v]>dist[u]+w){
                dist[v]=dist[u]+w;
                if(!enter[v]){
					if(++update[v]>n) return -1;
                    enter[v]=true;
                    q[t]=v;
                    t=(t+1)%N;
                }
            }
        }
    }
    if(dist[n]==0x3f3f3f3f) return -2;
    else return dist[n];
}
int main(){
    scanf("%d%d%d",&n,&m1,&m2);
    prepareGraph(),prepareSPFA();
    for(int i=1;i<=n;i++) addEdge(0,i,0);
    for(int i=1;i<n;i++) addEdge(i+1,i,0);
    for(int i=1,u,v,w;i<=m1;i++){
        scanf("%d%d%d",&u,&v,&w);
        if(u>v) swap(u,v);
        addEdge(u,v,w);
    }
    for(int i=1,u,v,w;i<=m2;i++){
        scanf("%d%d%d",&u,&v,&w);
        if(u>v) swap(u,v);
        addEdge(v,u,-w);
    }
    if(spfa(0)==-1) puts("-1");
    else prepareSPFA(),printf("%d\n",spfa(1));
    return 0;
}
posted @ 2025-04-26 22:39  九三青梧  阅读(9)  评论(0)    收藏  举报