3. C - Admiral

题意:给定v(3<=v<=1000)个节点,e(3<=e<=10000)条边的又向加权图,求1->v的两条不相交的路径,使得权和最小。

思路:

拆点+最小费用最大流

解题代码:

#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
using namespace std;
#define rep(i,a,n) for(int i = a; i < n; i++)
#define repe(i,a,n) for(int i = a; i <= n; i++)
#define clc(a,b) memset(a,b,sizeof(a))
#define MAXN 2010
#define INF 0x3f3f3f3f
typedef long long LL;
struct MCMF{
int n,m;
struct Edge{
int from, to, cap, flow, cost;
Edge(int a, int b, int c, int d, int e){
from = a, to = b, cap = c, flow = d, cost = e;
}
};
vector<Edge> edge;
vector<int> g[MAXN];
bool inq[MAXN];
int d[MAXN]/*spfa*/, p[MAXN]/*上一条弧*/, a[MAXN]/*可改进量*/;
void init(int n){
this->n = n;
repe(i,1,n) g[i].clear();
edge.clear();
}
void add_edge(int from, int to, int cap, int cost)
{
edge.push_back(Edge(from,to,cap,0,cost));
edge.push_back(Edge(to,from,0,0,-cost));
m = edge.size();
g[from].push_back(m-2);
g[to].push_back(m-1);
}
bool spfa(int s, int t, int& flow, LL& cost)
{
clc(d,0x3f);
clc(inq,0);
d[s] = 0, inq[s] = true, p[s] = 0, a[s] = INF;
queue<int> q;
q.push(s);
while(!q.empty())
{
int u = q.front();q.pop();
inq[u] = false;
int sz = g[u].size();
rep(i,0,sz)
{
Edge& e = edge[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] = true;
}
}
}
if(INF == d[t]) return false;
flow += a[t];
cost += (LL)d[t]*(LL)a[t];
for(int u = t; u != s; u = edge[p[u]].from)
{
edge[p[u]].flow += a[t];
edge[p[u]^1].flow -= a[t];
}
return true;
}
//需要保证初始网络没有负圈,返回最大流量,cost才是最小花费
int mincostmaxflow(int s, int t, LL & cost)
{
int flow = 0;
cost = 0;
while(spfa(s,t,flow,cost));
return flow;
}
}mcmf; int main()
{
#ifdef SHY
freopen("e:\\1.txt","r",stdin);
#endif
int n,m;
while(~scanf("%d %d%*c", &n, &m))
{
int a,b,c;
mcmf.init(n<<1);
rep(i,2,n) mcmf.add_edge(i,i+n,1,0);
mcmf.add_edge(1,n+1,2,0);
mcmf.add_edge(n,n<<1,2,0);
rep(i,0,m)
{
scanf("%d %d %d%*c", &a, &b, &c);
mcmf.add_edge(a+n,b,1,c);
}
LL ans;
mcmf.mincostmaxflow(1,n<<1,ans);
printf("%lld\n", ans);
}
return 0;
}

最新文章

  1. C# 集合已修改;可能无法执行枚举操作
  2. gulp配置文件备份
  3. 网络编程--ASI--(ASIHTTPRequest)介绍
  4. APDU
  5. iOS - CoreMotion
  6. [unroll(num)] for(int i;i&lt;num;i++)
  7. 找斐波那契数列中的第N个数——递归与函数自调用算法
  8. win10 uwp DataContext
  9. freemarker中的left_pad和right_pad
  10. 软件测试-chapter2-homework2
  11. Kaggle比赛NCFM图像分类任务简介
  12. css清除常用默认样式表
  13. libgdx学习记录27——线段与线段相交检测
  14. 加强对HEAD 请求的处理(转贴)
  15. 【洛谷P1330】封锁阳光大学
  16. Linux反编译
  17. 如何开启GZIP
  18. P1474 货币系统 Money Systems
  19. DMZ靶场渗透
  20. vue+element ui项目总结点(四)零散细节概念巩固如vue父组件调用子组件的方法、拷贝数据、数组置空问题 等

热门文章

  1. jquery 深入学习笔记之中的一个 (事件绑定)
  2. 距特征之k阶距概念
  3. c++vector简单实现
  4. Codeforces Round #422 (Div. 2) D. My pretty girl Noora 数学
  5. Spring中的AOP(学习笔记)
  6. SD/MMC异同
  7. 微信公众号菜单与应用交互session
  8. Scrapy运行报错:ModuleNotFoundError: No module named &#39;douban.douban&#39;
  9. Python小练习_将数据库中表数据存到redis里
  10. https证书/即SSL数字证书申请途径和流程