2020牛客多校十J Identical Trees

https://ac.nowcoder.com/acm/contest/5675/J
题意:给两颗同构树,问把第一个变成第二个的最少操作。
思路:dfs+二分图最小权完美匹配
假如说现在尝试改同构:原树的r1这个子树,终树的r2这个子树。就枚举r1的s1个子树和r2的s2个子树,s1*s2种组合,每种分别dfs看看能不能使之同构,(建个二分图,左边s1个点,右边s2个)能的话就这两个点连一条权值为需要几次修改的边,求一个最小权的完美匹配就把r1和r2搞同构了

这个方法看起来复杂度非常高,是远远过不了的,可实际上飞快,二十几毫秒,这是为什么呢?怎么算呢?

#include
using namespace std;
const int maxn=550;
typedef long long ll;
const int INF=0x3f3f3f3f;

int n;
vector<int> son1[maxn],son2[maxn];

struct Edge{
	int from,to,cap,flow,cost;
};

struct MCMF{
	int n,m,s,t;
	vector<Edge> edges;
	vector<int> G[maxn];
	int inq[maxn];
	ll d[maxn];
	int p[maxn];
	int a[maxn];

	void init(int s1,int s2)
	{
        n=s1+s2+1;
        s=s1+s2,t=s+1;
        for(int i=0;i<=t;i++)G[i].clear();
        edges.clear();
        for(int i=0;i<s1;i++)AddEdge(s,i,1,0);
        for(int i=s1;i<s1+s2;i++)AddEdge(i,t,1,0);
	}

	void AddEdge(int from,int to,int cap,int cost)
	{
		edges.push_back((Edge){from,to,cap,0,cost});
		edges.push_back((Edge){to,from,0,0,-cost});
		m=edges.size();
		G[from].push_back(m-2);
		G[to].push_back(m-1);
	}

	bool BellmanFord(ll& flow,ll& cost)
	{
		for(int i=0;i<=t;i++)d[i]=(1LL<<50);/***切记这里要改***/
		memset(inq,0,sizeof(inq));
		d[s]=0;inq[s]=1;p[s]=0;a[s]=INF;//流量INF

		queue<int> Q;
		Q.push(s);
		while(!Q.empty())
		{
			int u=Q.front();Q.pop();
			inq[u]=0;
			for(int i=0;i<G[u].size();i++)
			{
				Edge& e=edges[G[u][i]];
				if(e.cap>e.flow && d[e.to]>d[u]+e.cost)
				{
					d[e.to]=d[u]+e.cost;
					p[e.to]=G[u][i];
					a[e.to]=min(a[u],e.cap-e.flow);
					if(inq[e.to]==0){inq[e.to]=1;Q.push(e.to);}
				}
			}
		}
		if(d[t]==(1LL<<50))return false;/***切记这里要改***/
		flow+=a[t];
		cost+=a[t]*d[t];
		int u=t;
		while(u!=s)
		{
			edges[p[u]].flow+=a[t];
			edges[p[u]^1].flow-=a[t];
			u=edges[p[u]].from;
		}
		return true;
	}

	ll Mincost(int &f)
	{
		ll flow=0,cost=0;
		while(BellmanFord(flow,cost));
        f=flow;
		return cost;
	}
}ans;

int dfs(int r1,int r2)
{   
    int s1=son1[r1].size(),s2=son2[r2].size();
    if(s1!=s2)return -1;
    vector<int> e[3];  
    for(int i=0;i<s1;i++)
        for(int j=0;j<s2;j++)
        {
            int x=dfs(son1[r1][i],son2[r2][j]);
            if(x!=-1)e[0].push_back(i),e[1].push_back(s1+j),e[2].push_back(x);
        }
    ans.init(s1,s2);  
    for(int x=0;x<e[0].size();x++){ans.AddEdge(e[0][x],e[1][x],1,e[2][x]);}
    int f;
    int tmp=ans.Mincost(f);
    if(f!=s1)return -1;
    if(r1!=r2)tmp++;
    return tmp;
}

int main()
{
    //freopen("input.in","r",stdin);
    cin>>n;
    int x;
    for(int i=1;i<=n;i++)cin>>x,son1[x].push_back(i);
    for(int i=1;i<=n;i++)cin>>x,son2[x].push_back(i);
    int r1=son1[0][0],r2=son2[0][0];
    cout<<dfs(r1,r2)<<endl;
    return 0;
}

你可能感兴趣的:(DFS,二分图,网络流)