Graph 如何在给定的图中找到最大的二部子图?

Graph 如何在给定的图中找到最大的二部子图?,graph,depth-first-search,bipartite,subgraph,cyclic,Graph,Depth First Search,Bipartite,Subgraph,Cyclic,给定一个无向无权图:它可能是循环的,每个顶点都有给定的值,如图所示 查找最大的二部子图的大小(最大表示该图中的最大顶点数(已连接) 答复: 最大的图形是橙色的,所以答案是8 我的做法: #define loop(i,n) for(int i=0;i<n;i++) int vis[N+1]; vector<int> adj[N+1] // graph in adjacency vec

给定一个无向无权图:它可能是循环的,每个顶点都有给定的值,如图所示

查找最大的二部子图的大小(最大表示该图中的最大顶点数(已连接)

答复:

最大的图形是橙色的,所以答案是8

我的做法:

#define loop(i,n) for(int i=0;i<n;i++)                                    
int vis[N+1];
vector<int> adj[N+1]            // graph in adjacency vector list
int dfs(int current_vertex,int parent,int original_value,int other_value){
    int ans=0;
    vis[current_vertex]=1;                    // mark as visited  

    // map for adding values from neighbours having same value   
    map<int,int> mp;  
    // if curr vertex has value original_value then look for the neighbours  
    // having value as other,but if other is not defined define it   

    if(value[current_vertex]==original_value){   
        loop(i,adj[current_vertex].size()){
            int v=adj[current_vertex][i];
            if(v==parent)continue;
            if(!vis[v]){
                if(value[v]==other_value){
                   mp[value[v]]+=dfs(v,current_vertex,original,other);
                }
                else if(other==-1){  
                   mp[value[v]]+=dfs(v,current_vertex,original,value[v]);
                }
            }
        }
    }
   //else if the current_vertex has other value than look for original_value
    else{
        loop(i,adj[current_vertex].size()){
            int v=adj[current_vertex][i];
            if(v==p)continue;
            if(!vis[v]){
                if(value[v]==original){
                    mp[value[v]]+=dfs(v,current_vertex,original,other);
                }
            }
        }
    }    
    // find maximum length that can be found from neighbours of curr_vertex
    map<int,int> ::iterator ir=mp.begin();
    while(ir!=mp.end()){
        ans=max(ans,ir->second);
        ir++;
    }   
    return ans+1;
} 
#为(int i=0;isecond)定义循环(i,n);
ir++;
}   
返回ans+1;
} 
电话:

// N is the number of vertices in original graph : n=|V|
for(int i=0;i<N;i++){  
    ans=max(ans,dfs(i,-1,value[i],-1);  
    memset(vis,0,sizeof(vis));  
}
//N是原始图形中的顶点数:N=|V|

对于(int i=0;i这似乎并不难。遍历边列表,并将每个边添加到由顶点标签规范对(图中的1,2,3,例如,该对中的第一个顶点标签值最低)设置关键帧的多重映射中

现在,对于多重贴图(边列表)中的每个值,累加相应的顶点集

最大顶点集对应于最大二部图的边

该算法遍历每条边两次,对每条边执行固定数量的map和set操作,因此其分摊的运行时间和空间实际上是O(| V |+| E |)


请注意,使用邻接列表表示可能比使用矩阵表示更简单,因为列表显式地给出了边。矩阵需要更仔细的遍历(如DFS)以避免ω(| V | ^2)性能。

欢迎访问堆栈溢出。请阅读关于如何提问的帮助,尤其是关于。您甚至没有解释过您的图形表示。它要求大量改进以混乱的C++给出的算法。无论如何,我怀疑您会找到一个正确的算法,它不会以某种方式触摸所有边缘。算法可以做到。我现在已经完成了编辑