3435==1853==3488 三连发

xiaoxiao2021-02-28  25

确实没啥意思,谢了份代码愣交,就是爽一爽,舒服点好去补一发 变5.。。

#include<cstdio> #include<queue> #include<iostream> #include<cstring> #include<algorithm> using namespace std; const int maxn=200001; const int inf=0x3f3f3f3f; int n,m,ss,tt; int cost[100005]; struct Edge{ int from,to,cap,flow,cost;//出点,入点,容量,当前流量,费用(也就是权值) Edge(int u,int v,int c,int f,int w):from(u),to(v),cap(c),flow(f),cost(w){} }; struct MCMF{ int n,m; vector<Edge> edges;//保存表 vector<int> G[maxn];//保存邻接关系 int inq[maxn];//判断一个点是否在队列当中(SPFA算法当中要用) int d[maxn];//起点到d[i]的最短路径保存值 int p[maxn];//用来记录路径,保存上一条弧 int a[maxn];//找到增广路径后的改进量 void init(int n){ //初始化 this->n=n; for(int i=0;i<=n;i++) G[i].clear(); edges.clear(); } void AddEdge(int from,int to,int cap,int cost){ edges.push_back(Edge(from,to,cap,0,cost));//正向 edges.push_back(Edge(to,from,0,0,-cost));//反向 m=edges.size(); G[from].push_back(m-2);//按照边的编号保存邻接关系 G[to].push_back(m-1); } bool BellmanFord(int s,int t,int& flow,long long& cost){ for(int i=0;i<=n;i++) d[i]=inf; memset(inq,0,sizeof(inq)); d[s]=0; inq[s]=1; p[s]=0; a[s]=inf; queue<int> Q; Q.push(s); while(!Q.empty()){ int u=Q.front(); Q.pop(); inq[u]=0; for(int i=0;i<G[u].size();i++){ Edge& e=edges[G[u][i]]; if(e.cap>e.flow&&d[e.to]>d[u]+e.cost){ d[e.to]=d[u]+e.cost; p[e.to]=G[u][i]; a[e.to]=min(a[u],e.cap-e.flow); if(!inq[e.to]){ Q.push(e.to); inq[e.to]=1; } } } } if(d[t]==inf) return false; flow+=a[t]; cost+=(long long )d[t]*(long long)a[t]; for(int u=t;u!=s;u=edges[p[u]].from){ edges[p[u]].flow+=a[t]; edges[p[u]^1].flow-=a[t]; } return true; } int MincostMaxflow(int s,int t,int num){ int flow = 0; long long cost=0; while(BellmanFord(s,t,flow,cost)); return flow==num? cost:-1; //(有向环最小权值覆盖这么写) } }g; int minv[1005][1005]; int main(){ int t,cases=1; scanf("%d",&t); while(t--){ scanf("%d%d",&n,&m); memset(minv,inf,sizeof(minv)); ss=0;tt=2*n+1; g.init(2*n+2); for(int i=1;i<=n;i++){ g.AddEdge(ss,i,1,0); g.AddEdge(i+n,tt,1,0); } for(int i=0;i<m;i++){ int a,b,c; scanf("%d%d%d",&a,&b,&c); if(c<minv[a][b]){ g.AddEdge(a,b+n,1,c); g.AddEdge(b,a+n,1,c); minv[a][b]=c; } } int ans=g.MincostMaxflow(ss,tt,n); if(ans!=-1) printf("Case %d: %d\n",cases++,ans); else printf("Case %d: NO\n",cases++); } return 0; }

转载请注明原文地址: https://www.6miu.com/read-1449979.html

最新回复(0)