回溯法之最大团问题
源代码
#include<iostream>
#include<cstdlib>
using namespace std;
int** getM(int n){
int **M=(int**)malloc(sizeof(int*)*(n));
for(int i=0;i<n;i++){
M[i]=(int*)malloc(sizeof(int)*(n));
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
M[i][j]=0;
}
}
return M;
}
void freeM(int**M,int n){
for(int i=0;i<n;i++){
free(M[i]);
}
free(M);
}
void printM(int**M,int n){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<M[i][j]<<"\t";
}
cout<<endl;
}
}
bool Judge(int**M,int u,int t,bool* tempChoose){
bool return_bool=true;
for(int i=0;i<t;i++){
if(tempChoose[i]&&M[t][i]==0){
return_bool=false;
break;
}
}
return return_bool;
}
void Backtrack(int t,int**M,int u,bool*bestChoose,int*bestCount,bool *tempChoose,int*tempCount){
if(t>=u){
for(int i=0;i<u;i++){
bestChoose[i]=tempChoose[i];
}
*bestCount=*tempCount;
return;
}
if(Judge(M,u,t,tempChoose)){
tempChoose[t]=true;
*tempCount=(*tempCount)+1;
Backtrack(t+1,M,u,bestChoose,bestCount,tempChoose,tempCount);
*tempCount=(*tempCount)-1;
}
if((*tempCount)+u-t>*bestCount){
tempChoose[t]=false;
Backtrack(t+1,M,u,bestChoose,bestCount,tempChoose,tempCount);
}
}
int main(int argc,char**argv){
int u,v;
cout<<"input people count\n";
cin>>u;
cout<<"relation count\n";
cin>>v;
int**M=getM(u);
cout<<"input relation\n";
for(int i=0;i<v;i++){
int u1,u2;
cin>>u1>>u2;
M[u2][u1]=M[u1][u2]=1;
}
cout<<"relation map\n";
printM(M,u);
bool*bestChoose=(bool*)malloc(sizeof(bool)*u);
bool*tempChoose=(bool*)malloc(sizeof(bool)*u);
for(int i=0;i<u;i++){
bestChoose[i]=false;
}
int bestCount=0;
int tempCount=0;
Backtrack(0,M,u,bestChoose,&bestCount,tempChoose,&tempCount);
cout<<"Best Choose\n";
for(int i=0;i<u;i++){
if(bestChoose[i]==true){
cout<<i<<"\t";
}
}
cout<<endl;
cout<<"BestCount\n";
cout<<bestCount<<endl;
free(M);
free(bestChoose);
free(tempChoose);
return 0;
}
测试样例
input people count
5
relation count
8
input relation
0 1
0 2
0 3
0 4
1 2
2 3
2 4
3 4
relation map
0 1 1 1 1
1 0 1 0 0
1 1 0 1 1
1 0 1 0 1
1 0 1 1 0
Best Choose
0 2 3 4
BestCount
4
--------------------------------
Process exited after 9.083 seconds with return value 0
请按任意键继续. . .