费用流,拆成二分图处理加上S和T直接搞
不用调试1A开心
/************************************************************** Problem: 1927 User: BPM136 Language: C++ Result: Accepted Time:2216 ms Memory:2028 kb ****************************************************************/ #include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<cstdlib> #include<algorithm> #include<bitset> #define LL long long #define fo(i,a,b) for(int i=a;i<=b;i++) #define efo(i,x) for(int i=last[x];i!=0;i=e[i].next) using namespace std; inline LL read() { LL d=0,f=1;char s=getchar(); while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();} while(s>='0'&&s<='9'){d=d*10+s-'0';s=getchar();} return d*f; } #define N 805 #define M 15005 #define inf 1000000000 struct edge { int y,f,c,next; }e[M*3]; int last[N*2],ne=1; int n,m,ans=0; int S,T; int dis[N*2],lo[N*2],pre[N*2]; int q[N*9]; bitset<N*2>inq; bool spfa(int s,int tt) { memset(pre,0,sizeof(pre)); memset(lo,0,sizeof(lo)); fo(i,0,N*2-1)dis[i]=inf; inq.reset(); int h=0,t=1; inq[s]=1;q[1]=s;dis[s]=0; while(h<t) { int now=q[++h]; efo(i,now) if(e[i].f&&dis[now]+e[i].c<dis[e[i].y]) { dis[e[i].y]=dis[now]+e[i].c; lo[e[i].y]=i; pre[e[i].y]=now; if(inq[e[i].y]==0) { inq[e[i].y]=1; q[++t]=e[i].y; } } inq[now]=0; } if(dis[tt]==inf)return 0; else return 1; } void mcf(int s,int t) { while(spfa(s,t)) { int x=t,mi=inf; while(pre[x]!=0) { mi=min(mi,e[lo[x]].f); x=pre[x]; } x=t; while(pre[x]!=0) { ans+=mi*e[lo[x]].c; e[lo[x]].f-=mi; e[lo[x]^1].f+=mi; x=pre[x]; } } } void add(int x,int y,int f,int c) { e[++ne].y=y;e[ne].f=f;e[ne].c=c;e[ne].next=last[x];last[x]=ne; } void add2(int x,int y,int f,int c) { add(x,y,f,c);add(y,x,0,-c); } void init() { n=read(),m=read(); S=2*n+1;T=S+1; fo(i,1,n) { int x=read(); add2(S,i+n,1,x); } fo(i,1,m) { int x=read(),y=read(),w=read(); if(x>y)swap(x,y); add2(x,y+n,1,w); } fo(i,1,n) { add2(S,i,1,0); add2(n+i,T,1,0); } } int main() { init(); mcf(S,T); cout<<ans<<endl; return 0; }