0-1背包
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct VER
{
int w;
int v;
} ;
#define N 100
int x[ N] ;
int n, c;
int CurWeight = 0 ;
int CurValue = 0 ;
int BestValue = 0 ;
int BestX[ N] ;
VER ver[ N] ;
void input ( )
{
cout<< "请输入物品的个数:" << endl;
cin>> n;
cout<< "请输入每个物品的重量及价值:" << endl;
for ( int i = 1 ; i <= n; i++ )
{
cin>> ver[ i] . w>> ver[ i] . v;
}
cout<< "请输入背包的容量:" << endl;
cin>> c;
}
void output ( )
{
cout<< "最优值是:" << BestValue<< endl;
cout<< "(" ;
for ( int i= 1 ; i<= n; i++ )
cout<< BestX[ i] << " " ;
cout<< ")" ;
}
void backtrack ( int t)
{
if ( t> n)
{
if ( CurValue> BestValue)
{
BestValue = CurValue;
for ( int i= 1 ; i<= n; ++ i)
BestX[ i] = x[ i] ;
}
}
else
{
for ( int i= 0 ; i<= 1 ; ++ i)
{
x[ t] = i;
if ( i== 0 )
{
backtrack ( t+ 1 ) ;
}
else
{
if ( ( CurWeight+ ver[ t] . w) <= c)
{
CurWeight + = ver[ t] . w;
CurValue + = ver[ t] . v;
backtrack ( t+ 1 ) ;
CurWeight - = ver[ t] . w;
CurValue - = ver[ t] . v;
}
}
}
}
}
int main ( )
{
input ( ) ;
backtrack ( 1 ) ;
output ( ) ;
return 0 ;
}
八皇后
#include <iostream>
#include <algorithm>
using namespace std;
#define N 8
int chess[ N] [ N] = { 0 } ;
void print ( int c)
{
cout<< "解法" << c;
cout<< ":" << endl;
for ( int i= 0 ; i< N; i++ )
{
for ( int j= 0 ; j< N; j++ )
{
if ( chess[ i] [ j] == 1 )
{
cout<< "C " ;
}
else {
cout<< "* " ;
}
}
cout<< endl;
}
cout<< endl;
}
bool pot ( int row, int col)
{
int i, j;
for ( i= 0 ; i< N; i++ )
{
if ( chess[ i] [ col] == 1 )
{
return false ;
}
}
for ( i= row, j= col; i>= 0 && j>= 0 ; i-- , j-- )
{
if ( chess[ i] [ j] == 1 )
{
return false ;
}
}
for ( i= row, j= col; i>= 0 && j< N; i-- , j++ )
{
if ( chess[ i] [ j] == 1 )
{
return false ;
}
}
return true ;
}
int eightqueen ( int row, int & c)
{
if ( row> 7 )
{
c++ ;
print ( c) ;
return c;
}
for ( int i= 0 ; i< N; i++ )
{
if ( pot ( row, i) )
{
chess[ row] [ i] = 1 ;
eightqueen ( row+ 1 , c) ;
chess[ row] [ i] = 0 ;
}
}
return 0 ;
}
int main ( )
{
int count= 0 ;
eightqueen ( 0 , count) ;
cout<< "The total solutions:" << count<< endl;
return 0 ;
}