G. Petya and Graph

time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output

Petya has a simple graph (that is, a graph without loops or multiple edges) consisting of n vertices and m edges.

The weight of the i-th vertex is ai.

The weight of the i-th edge is wi.

A subgraph of a graph is some set of the graph vertices and some set of the graph edges. The set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices.

The weight of a subgraph is the sum of the weights of its edges, minus the sum of the weights of its vertices. You need to find the maximum weight of subgraph of given graph. The given graph does not contain loops and multiple edges.

Input
The first line contains two numbers n and m (1≤n≤103,0≤m≤103) - the number of vertices and edges in the graph, respectively.

The next line contains n integers a1,a2,…,an (1≤ai≤109) - the weights of the vertices of the graph.

The following m lines contain edges: the i-e edge is defined by a triple of integers vi,ui,wi (1≤vi,ui≤n,1≤wi≤109,vi≠ui). This triple means that between the vertices vi and ui there is an edge of weight wi. It is guaranteed that the graph does not contain loops and multiple edges.

Output
Print one integer — the maximum weight of the subgraph of the given graph.

Examples
inputCopy

4 5
1 5 2 2
1 3 4
1 4 4
3 4 5
3 2 2
4 2 2
outputCopy
8
inputCopy
3 3
9 7 8
1 2 1
2 3 2
1 3 3
outputCopy
0
Note
In the first test example, the optimal subgraph consists of the vertices 1,3,4 and has weight 4+4+5−(1+2+2)=8. In the second test case, the optimal subgraph is empty.


最大权闭合子图。

现在感觉网络流就两种:

  1. sb建图,这么明显
  2. 还能这样玩?

太难了!!!!!!


选物品得到价值,但是物品选取有条件,条件要花费代价,很明显的最小割。

建图即可。


AC代码:

#pragma GCC optimize(2)
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int inf=0x3f3f3f3f3f3f3f3f;
const int N=2e3+10,M=1e5+10;
int n,m,h[N],s,t,res,cnt;
int head[N],nex[M],to[M],w[M],tot=1;
inline void ade(int a,int b,int c){
	to[++tot]=b; nex[tot]=head[a]; w[tot]=c; head[a]=tot;
}
inline void add(int a,int b,int c){
	ade(a,b,c);	ade(b,a,0);
}
inline int bfs(){
	queue<int> q;	q.push(s);	memset(h,0,sizeof h); h[s]=1;
	while(q.size()){
		int u=q.front();	q.pop();
		for(int i=head[u];i;i=nex[i]){
			if(w[i]&&!h[to[i]]){
				h[to[i]]=h[u]+1;	q.push(to[i]);
			}
		}
	}
	return h[t];
}
int dfs(int x,int f){
	if(x==t)	return f; int fl=0;
	for(int i=head[x];i&&f;i=nex[i]){
		if(w[i]&&h[to[i]]==h[x]+1){
			int mi=dfs(to[i],min(w[i],f));
			w[i]-=mi; w[i^1]+=mi; fl+=mi; f-=mi;
		}
	}
	if(!fl)	h[x]=-1;
	return fl;
}
int dinic(){
	int res=0;
	while(bfs())	res+=dfs(s,inf);
	return res;
}
signed main(){
	cin>>n>>m; t=n+m+1;
	for(int i=1,x;i<=n;i++)	cin>>x,add(i,t,x);
	for(int i=1,u,v,w;i<=m;i++){
		cin>>u>>v>>w;	res+=w;	add(s,i+n,w);
		add(i+n,u,inf);	add(i+n,v,inf);
	}
	cout<<res-dinic()<<endl;
	return 0;
}