将一个无向图分成许多回路,回路点交集为空,点幷集为V。幷最小化回路边权和。

 #include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#define maxn 2010
#define oo 0x3f3f3f3f
using namespace std; struct Edge {
int u, v, c, f;
Edge( int u, int v, int c, int f ):u(u),v(v),c(c),f(f){}
};
struct Mcmf {
int n, src, dst;
vector<Edge> edge;
vector<int> g[maxn];
int dis[maxn], pth[maxn], ext[maxn]; void init( int n, int src, int dst ) {
this->n = n;
this->src = src;
this->dst = dst;
for( int u=; u<=n; u++ )
g[u].clear();
edge.clear();
}
void add_edge( int u, int v, int c, int f ) {
g[u].push_back( edge.size() );
edge.push_back( Edge(u,v,c,f) );
g[v].push_back( edge.size() );
edge.push_back( Edge(v,u,-c,) );
}
bool spfa( int &flow, int &cost ) {
queue<int> qu;
memset( dis, 0x3f, sizeof(dis) );
qu.push( src );
dis[src] = ;
pth[src] = -;
ext[src] = true;
while( !qu.empty() ) {
int u=qu.front();
qu.pop();
ext[u] = false;
for( int t=; t<g[u].size(); t++ ) {
Edge &e = edge[g[u][t]];
if( e.f && dis[e.v]>dis[e.u]+e.c ) {
dis[e.v] = dis[e.u]+e.c;
pth[e.v] = g[u][t];
if( !ext[e.v] ) {
ext[e.v] = true;
qu.push( e.v );
}
}
}
}
if( dis[dst]==oo ) return false;
int flw = oo;
for( int eid=pth[dst]; eid!=-; eid=pth[edge[eid].u] )
flw = min( flw, edge[eid].f );
for( int eid=pth[dst]; eid!=-; eid=pth[edge[eid].u] ) {
edge[eid].f -= flw;
edge[eid^].f += flw;
}
flow += flw;
cost += flw*dis[dst];
return true;
}
bool mcmf( int &flow, int &cost ) {
flow = cost = ;
while(spfa(flow,cost));
return true;
}
}; int n, m;
Mcmf M; int main() {
int T;
scanf( "%d", &T );
for( int cas=; cas<=T; cas++ ) {
printf( "Case %d: ", cas );
scanf( "%d%d", &n, &m );
M.init( n+n+, n+n+, n+n+ );
for( int i=,u,v,w; i<=m; i++ ) {
scanf( "%d%d%d", &u, &v, &w );
M.add_edge( u, v+n, w, );
M.add_edge( v, u+n, w, );
}
for( int u=; u<=n; u++ ) {
M.add_edge( M.src, u, , );
M.add_edge( u+n, M.dst, , );
}
int flow, cost;
M.mcmf( flow, cost );
if( flow!=n ) printf( "NO\n" );
else printf( "%d\n", cost );
}
}

最新文章

  1. 带你玩转Visual Studio
  2. 转:linux coredump调试
  3. AC日记——单词替换 1.7 21
  4. python学习第三天
  5. [HDOJ4325]Flowers(树状数组 离散化)
  6. bzoj1930
  7. 用NGUI做一个计时条!
  8. Legal or Not
  9. EBS FORM FOLDER 开发,单元格无法使用右键
  10. UVA - 11082 Matrix Decompressing(最大流+行列模型)
  11. js jq 字符串数组对象
  12. PAT基础6-6
  13. 浅谈Java对象的equals方法
  14. ReactiveCocoa基础
  15. C#内存压缩zip文件
  16. [Android] 使用ViewPager 实现导航
  17. Nanami&#39;s Digital Board CodeForces - 434B (棋盘dp)
  18. Oracle创建数据库链接
  19. angular指令的详细讲解,不断补充
  20. php file_exists中文路径不存在问题

热门文章

  1. spring mvc convention over configuration 之 RequestToViewNameTranslator
  2. wget下载整个网站或特定目录
  3. Python3中字符串的编码与解码以及编码之间转换(decode、encode)
  4. python 异常知识点
  5. CentOS7.4 安装 oracle12c
  6. SYN Flood攻击及防御方法 (转)
  7. Oracle常用sql语句(三)之子查询
  8. 简单优化:Zipalign
  9. Linux 基础——常用的Linux网络命令
  10. JavaWeb知识回顾-Servlet常用类、接口及其方法