【发布时间】:2018-06-07 05:20:36
【问题描述】:
给定一个无向无权图:它可能是循环的,并且每个顶点都有给定值,如图所示。
找到最大的 Bi-Partite 子图的大小(最大意味着该图中的最大顶点数(连接))?
答案:
最大的图表是橙色的,所以答案是 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;
}
调用:
// 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));
}
但我想改进它以在O(|V|+|E|) 时间运行。 |V| 是顶点数,|E| 是边数,我该怎么做?
【问题讨论】:
-
欢迎堆栈溢出。请阅读有关如何提问的帮助,尤其是关于 minimum, complete, verifiable examples 的帮助。你甚至没有解释你的图形表示。改进作为杂乱 C++ 给出的算法需要很多。无论如何,我怀疑你会找到一个不会以某种方式触及所有边缘的正确算法。没有 O(|V|) 算法可以做到这一点。
-
我已经完成了编辑
标签: c++ graph depth-first-search bipartite subgraph