NOI 2006 最大获利 (最大权闭合子图)

来源:互联网 发布:多因子选股 知乎 编辑:程序博客网 时间:2024/05/14 12:29

点击打开链接

比较模版的最大权闭合子图。

代码如下:

#include<iostream>#include<cstring>#include<cstdio>#include<queue>const int maxn = 55005;const int maxm = 1e6;const int INF = 0x3f3f3f3f;using namespace std;inline int read(){int x=0,t=1,c;while(!isdigit(c=getchar()))if(c=='-')t=-1;while(isdigit(c))x=x*10+c-'0',c=getchar();return x*t;}int head[maxn],cur[maxn],nx[maxm<<1],to[maxm<<1],flow[maxm<<1],ppp=0;struct Dinic{int dis[maxn];int s, t;long long ans;void init() {memset(head, -1, sizeof(head));ppp = 0;}void AddEdge(int u, int v, int c){to[ppp]=v;flow[ppp]=c;nx[ppp]=head[u];head[u]=ppp++;swap(u,v);to[ppp]=v;flow[ppp]=0;nx[ppp]=head[u];head[u]=ppp++;}bool BFS(){memset(dis, -1, sizeof(dis));dis[s] = 1; queue<int> Q;Q.push(s);while(!Q.empty()){int x = Q.front();Q.pop();for(int i = head[x]; ~i; i = nx[i]){if(flow[i] && dis[to[i]] == -1){dis[to[i]] = dis[x] + 1;Q.push(to[i]);}}}return dis[t] != -1;}int DFS(int x, int maxflow){if(x == t || !maxflow){ans += maxflow;return maxflow;}int ret = 0, f;for(int &i = cur[x]; ~i; i = nx[i]){if(dis[to[i]] == dis[x] + 1 && (f = DFS(to[i], min(maxflow, flow[i])))){ret += f;flow[i] -= f;flow[i^1] += f;maxflow -= f;if(!maxflow)break;}}return ret;}long long solve(int source, int tank){s = source;t = tank;ans = 0;while(BFS()){memcpy(cur, head, sizeof(cur));DFS(s, INF);}return ans;}}dinic;int main(){int n = read(), m = read();int s = 0, t = n + m + 1;dinic.init();for(int i = 1, p; i <= n; i++) {scanf("%d", &p);dinic.AddEdge(m + i, t, p);}long long cnt = 0;for(int i = 1; i <= m; i++) {int v1 = read(), v2 = read(), c = read();cnt += c;dinic.AddEdge(s, i, c);dinic.AddEdge(i, m + v1, INF);dinic.AddEdge(i, m + v2, INF);}printf("%lld\n", cnt - dinic.solve(s,t));return 0;}


阅读全文
0 0
原创粉丝点击