Gym - 101667E How Many to Be Happy?(最小生成樹,最大流最小割)

題目鏈接:Gym - 101667E How Many to Be Happy?

題意:

給出一含有n個結點和m條邊的圖G,定義該圖中的最小生成樹(MST)含有的邊爲happy,而不在MST中的邊爲unhappy,對於unhappy的邊e,刪除最少的邊數H(e)使得其變爲happy,求H(e)之和。



分析:

由MST的性質可知,對於任意一條不在MST中的邊e,會影響e構成MST的只有比它邊權小的邊,所以要刪除的邊只可能在這些比e邊權小的邊當中

將這些邊權比e小的邊選出後建圖(不包含e自身)設邊e的端點爲s、t

那麼只需要令s、t不連通,邊e就可以構成MST了,很明顯,問題就轉化爲了求最小割,那麼建圖的時候只需讓邊的容量爲1即可(求最小割時正向邊、反向邊容量相等)。



以下代碼:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
#include<algorithm>
#define LL long long
using namespace std;
const int INF=0x3f3f3f3f;
const int maxn=150;
const int maxm=550;
int n,m;
struct EDGE
{
    int u;
    int v;
    int w;
}E[maxm];
struct edge
{
    int w;
    int to;
    int next;
}e[maxm*2];
int head[maxn],cnt;
int s,t;
int depth[maxn],cur[maxn];
void addedge(int u,int v,int w)
{
    e[cnt].w=w;
    e[cnt].to=v;
    e[cnt].next=head[u];
    head[u]=cnt;
    cnt++;
    e[cnt].w=w;       //求最小割時反向邊容量不爲0
    e[cnt].to=u;
    e[cnt].next=head[v];
    head[v]=cnt;
    cnt++;
}
bool bfs()
{
    memset(depth,-1,sizeof(depth));
    queue<int> q;
    q.push(s);
    depth[s]=0;
    while(!q.empty())
    {
        int u=q.front();
        q.pop();
        for(int i=head[u];i!=-1;i=e[i].next)
        {
            int v=e[i].to;
            if(e[i].w>0&&depth[v]==-1)
            {
                depth[v]=depth[u]+1;
                q.push(v);
            }
        }
    }
    return depth[t]!=-1;
}
int dfs(int u,int flow)
{
    if(u==t)
        return flow;
    for(int &i=cur[u];i!=-1;i=e[i].next)
    {
        int v=e[i].to;
        if(depth[v]==depth[u]+1&&e[i].w>0)
        {
            int k=dfs(v,min(flow,e[i].w));
            if(k>0)
            {
                e[i].w-=k;
                e[i^1].w+=k;
                return k;
            }
        }
    }
    return 0;
}
int dinic()
{
    int ans=0;
    while(bfs())
    {
        for(int i=1;i<=n;i++)
            cur[i]=head[i];
        while(int k=dfs(s,INF))
            ans+=k;
    }
    return ans;
}
int main()
{
    scanf("%d %d",&n,&m);
    for(int i=0;i<m;i++)
        scanf("%d %d %d",&E[i].u,&E[i].v,&E[i].w);
    int he=0;
    for(int i=0;i<m;i++)
    {
        memset(head,-1,sizeof(head));
        cnt=0;
        for(int j=0;j<m;j++)
        {
            if(E[j].w<E[i].w)     //僅考慮邊權比i小的邊
                addedge(E[j].u,E[j].v,1);   //容量爲1
        }
        s=E[i].u;      //設定s、t
        t=E[i].v;
        he+=dinic();
    }
    printf("%d\n",he);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章