by back_tracker » Sun Jun 19, 2011 12:10 am
Hellow Guyssssssssssssssssssssss
it can be solved using back tracking algorithm.
1- check if u have the complete solution that is checking if you have colored all the nodes.
2- if yes, then save the information which are how many black nodes u have and what they are,
3- else, go to the next node and try to color it according to the rule, that it could be always white, but black only if there are no connected black nodes to it., (take all the possible colors for that nodes)
4- pick the first possible color, recur by going to step 1
5- then u should be able to come back to take the other possiblity of colors.
I have solved it and it works OK, but my code takes long time for some test cases, I wanna know WHY!!! and how can I iptimize my solution????
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<cmath>
using namespace std;
void Construct(bool c[], int &nCandidates, int edges, int **edge, int k, bool*a)
{
nCandidates=0;
bool legalblack= true;
for(int i =0; i<edges; i++)
{
if((edge[i][0]== k && a[edge[i][1]]== false ) || (edge[i][1]== k && a[edge[i][0]]== false ))
legalblack = false;
}
c[nCandidates] = true;
nCandidates++;
if(legalblack == true)
{
c[nCandidates] = false;
nCandidates++;
}
}
void back_track(vector<int> counter,vector<vector<int> > seq,int edges,int **edge, int nodes, int k,int index, bool *a, vector<int> &counterO,vector<vector<int> > &seqO, int &X)
{
bool c[2];
int nCandidates;
if(k == nodes)
{
counterO.push_back(counter[index]);
for(int j =0; j <seq[index].size(); j++)
{
seqO[X].push_back(seq[index][j]);
}
X++;
index++;
counter.push_back(0);
}
else{
k++;
Construct(c, nCandidates, edges, edge, k,a);
for(int i =0; i <nCandidates; i++)
{
a[k]= c[i];
if(a[k]== false)
{
counter[index]++;
seq[index].push_back(k);
}
back_track(counter,seq,edges,edge,nodes,k,index,a,counterO, seqO,X);
}
}
}
int main ()
{
int t;
cin>>t;
for(int i =0; i <t; i++)
{
int nodes;
int edges;
cin>>nodes>>edges;
int **edge = new int *[edges];
for(int i =0; i <edges; i++)
edge[i]= new int [2];
for(int i =0; i <edges; i++)
cin>>edge[i][0]>>edge[i][1];
vector<int> counter;
counter.push_back(0);
vector<vector<int> > seq (pow(2.0,double(nodes)));
vector<int> counterO;
vector<vector<int> > seqO(pow(2.0,double(nodes)));
bool *a= new bool[nodes+1];
int X=0;
back_track(counter,seq,edges,edge,nodes,0,0,a,counterO, seqO,X);
int max =0;
for(int i =0; i <counterO.size(); i++)
{
if(counterO[i]>max)
{
max= counterO[i];
}
}
for(int i =0; i <counterO.size(); i++)
{
if(counterO[i]== max)
{
cout<<counterO[i]<<endl;
for(int j =0; j <seqO[i].size(); j++)
cout<<seqO[i][j]<<" ";
cout<<endl;
break;
}
}
}
return 0;
}
//:D