您的位置:首页 > 其它

uva193 - Graph Coloring

2014-08-05 11:30 246 查看

GraphColoring

Youaretowriteaprogramthattriestofindanoptimalcoloringforagivengraph.Colorsareappliedtothenodesofthegraphandtheonlyavailablecolorsareblackandwhite.Thecoloringofthegraphiscalledoptimalifamaximumofnodesisblack.Thecoloringisrestrictedbytherulethatnotwoconnectednodesmaybeblack.


Figure:Anoptimalgraphwiththreeblacknodes

InputandOutput

Thegraphisgivenasasetofnodesdenotedbynumbers

,

,andasetofundirectededgesdenotedbypairsofnodenumbers

,

.Theinputfilecontainsmgraphs.Thenumbermisgivenonthefirstline.Thefirstlineofeachgraphcontainsnandk,thenumberofnodesandthenumberofedges,respectively.Thefollowingklinescontaintheedgesgivenbyapairofnodenumbers,whichareseparatedbyaspace.Theoutputshouldconsistsof2mlines,twolinesforeachgraphfoundintheinputfile.Thefirstlineofshouldcontainthemaximumnumberofnodesthatcanbecoloredblackinthegraph.Thesecondlineshouldcontainonepossibleoptimalcoloring.Itisgivenbythelistofblacknodes,separatedbyablank.

SampleInput

1
68
12
13
24
25
34
36
46
56

SampleOutput

3
145
求图的最大独立集,即把尽量多的结点图黑使得任意两个黑点不相邻

#include<cstdio>
#include<cstring>
#include<iostream>
#include<vector>
#include<algorithm>
usingnamespacestd;
constintmaxn=100+5;
intm,n,k;
vector<int>G[maxn];
intnode[maxn],black_node[maxn];
intans;
enum{white,black};

voiddfs(intd,intcnt){
if(d==n){
if(cnt>ans){
intj=0;
for(inti=0;i<n;i++)if(node[i])black_node[j++]=i+1;
ans=cnt;
}
return;
}

if(n-d+cnt<=ans)
return;
//尝试黑的
intok=true;
node[d]=black;
for(inti=0;i<G[d].size();i++){
intv=G[d][i];
//两个相邻黑点
if(node[v]==black){
ok=false;
break;
}
}
if(ok)dfs(d+1,cnt+1);

//尝试白的
node[d]=white;
dfs(d+1,cnt);
}

intmain()
{
#ifndefONLINE_JUDGE
freopen("./uva193.in","r",stdin);
#endif
intx,y;
cin>>m;
while(m--){
cin>>n>>k;
memset(G,0,sizeof(G));
memset(node,0,sizeof(node));
ans=0;
for(inti=0;i<k;i++){
cin>>x>>y;
x--;y--;
G[x].push_back(y);
G[y].push_back(x);
}
dfs(0,0);
printf("%d\n",ans);
for(inti=0;i<ans-1;i++)
printf("%d",black_node[i]);
printf("%d\n",black_node[ans-1]);

}

return0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: