poj 1129 Channel Allocation(DFS回溯)
1129 -- Channel Allocation (poj.org)
这道题的实质是图的着色问题,连通的结点不能用一种颜色
#include<iostream> #include<cstring> using namespace std; const int INF=0x3f3f3f3f; bool map[30][30]; int n,ans,color[26]; bool check(int pos,int color_index){ for(int i=0;i<n;i++){ if(map[pos][i]&&color[i]==color_index) return false; } return true; } void DFS(int index,int used_color_num){ if(used_color_num>=ans) return ; if(index==n){ ans=used_color_num; return ; } for(int i=1;i<=used_color_num;i++){ if(check(index,i)){ color[index]=i; DFS(index+1,used_color_num); color[index]=0; } } used_color_num++; color[index]=used_color_num; DFS(index+1,used_color_num); color[index]=0; } signed main(){ ios::sync_with_stdio(false); cin.tie(0);cout.tie(0); char str[30]; while(cin>>n && n){ memset(map,0,sizeof(map)); memset(color,0,sizeof(color)); ans=INF; for(int i=0;i<n;i++){ cin>>str; for(int j=2;j<strlen(str);j++) map[i][str[j]-'A']=true; } DFS(0,0); if(ans==1) cout<<ans<<" channel needed."<<endl; else cout<<ans<<" channels needed."<<endl; } return 0; }
下面是一个洛谷的简单版本:P2819 图的 m 着色问题 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
同样是DFS+check( )函数判断是否连通和颜色
#include<iostream> #include<cstring> using namespace std; bool v[110][110]; int n,k,m,ans,color[110]; bool check(int sum){ for(int i=1;i<=sum;i++){ if(v[i][sum] && color[i]==color[sum]) return false; } return true; } void DFS(int pos){ if(pos>n){ ans++; return ; } for(int i=1;i<=m;i++){ color[pos]=i; if(check(pos)) DFS(pos+1); else color[pos]=0; } } signed main(){ ios::sync_with_stdio(false); cin.tie(0);cout.tie(0); cin>>n>>k>>m; for(int i=1;i<=k;i++){ int x,y; cin>>x>>y; v[x][y]=true; v[y][x]=true; } memset(color,0,sizeof(color)); DFS(1); cout<<ans<<endl; return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)