acwing 2237. 猪

2237. 猪
分层图的简化,思路tql,大大的减少了点的基数

如果这个猪房已经被用过了,那就直接从用过的那个人哪里流过来就可以了
如果这个猪房没有用过,那就从超级起点流出来。
这样即舍去了,猪房这个点,还可以直接从人哪里进行转移,思路值得学习

//多个进行匹配的问题
#include <bits/stdc++.h>
using namespace std;
const int N=1005,M=1e6+5;
const int inf=1e9;
 
int h[N],ne[M],e[M],w[M],tot=1;
void add(int from,int to,int wi) {
    e[++tot]=to;  w[tot]=wi;  ne[tot]=h[from];  h[from]=tot;
    e[++tot]=from;w[tot]=0;   ne[tot]=h[to];    h[to]=tot;
}
 
int S=N-2,T=N-1;
int cur[N],dep[N];
bool bfs() {
    memcpy(cur,h,sizeof(h));
    memset(dep,0,sizeof(dep));
    queue<int>q;
    q.push(S);
    dep[S]=1;
    while(!q.empty()) {
        int now=q.front();
        q.pop();
        for(int i=h[now];i;i=ne[i]) {
            int to=e[i];
            if(dep[to]==0&&w[i]>0)
                dep[to]=dep[now]+1,q.push(to);
        }
    }
    return dep[T];
}
 
int dfs(int now,int sum) {
    if(now==T)return sum;
    int ans=0;
    for(int i=cur[now];i&&sum;i=ne[i]) {
        cur[now]=i;
        int to=e[i];
        if(dep[to]==dep[now]+1&&w[i]>0) {
            int k=dfs(to,min(sum,w[i]));
            if(k==0)dep[to]=0;
            w[i]-=k;
            w[i^1]+=k;
            sum-=k;
            ans+=k;
        }
    }
    return ans;
}
 
int dinic() {
    int ans=0;
    while(bfs())ans+=dfs(S,inf);
    return ans;
}

int c[N],pre[N];
int main() {
    int m,n;
    cin>>m>>n;
    for(int i=1;i<=m;i++)cin>>c[i];
    for(int i=1;i<=n;i++) {
        int a,b;cin>>a;
        while(a--) {
            int x;cin>>x;
            if(pre[x]==0)add(S,i,c[x]);
            else add(pre[x],i,inf);
            pre[x]=i;
        }
        cin>>b;
        add(i,T,b);
    }
    cout<<dinic()<<endl;
    return 0;
}
//对,如果没有动这个房子,那就相当于从起来流出来
//如果动了这个房子,那就从上一个人哪里流过来就行了
//点的数量很少,比直接分层图强多了
posted @ 2022-12-15 20:13  basicecho  阅读(38)  评论(0)    收藏  举报