这道题似乎也没什么剪枝可写,没有细想。 就是DFS。 还是,写代码的过程中牢牢记住DFS的思想即可。 代码如下: #include <iostream> #include <string> using namespace std; int rep[26][27],channelChosen[26]; bool check(int curRep,int curCha,int amount) { for (int j = 1;j <= rep[curRep][0];j++) { if(channelChosen[curRep]==channelChosen[rep[curRep][j]-1]) return false; } return true; } int DFS(int curRepeater,int curChannel,int num) { if(curRepeater>=num) return curChannel; for (int i = 1;i <= curChannel;i++) { channelChosen[curRepeater]=i; if(check(curRepeater,curChannel,num)) { return DFS(curRepeater+1,curChannel,num); } else continue; } channelChosen[curRepeater]=curChannel+1; return DFS(curRepeater+1,curChannel+1,num); } int main() { int numOfRepeaters; while (cin>>numOfRepeaters&&numOfRepeaters!=0) { string str; for (int i = 0;i < numOfRepeaters;i++) { cin>>str; int j = 1; string::iterator it = str.begin()+2; for (;it != str.end();it++) { rep[i][j++] = *it-'A'+1; } rep[i][0] = j-1; } int result = DFS(0,1,numOfRepeaters); string res = (result==1)?" channel needed.":" channels needed."; cout<<result<<res<<endl; } }