/* 利用穷举法解决组合问题
求n个自然数中r个数的组合,这里假设r=3.
例:如果n=3,则结果为:
4 3 2
4 3 1
4 2 1
3 2 1
*/
#include "stdio.h"
main()
{
int i,j,k,n;
FILE *fp;
if((fp=fopen("QingJu1.txt","wb"))==NULL)
{
printf("cannot open file ");
return;
}
printf("please input n:");
scanf("%d",&n);
for(i=n;i>=3;i--)
for(j=n-1;j>=2;j--)
for(k=j-1;k>=1;k--)
if((i!=j) && (j!=k) && (i!=k) && (i>j) && (j>k))
{
printf("%3d%3d%3d ",i,j,k); /*屏幕显示*/
fprintf(fp,"%3d%3d%3d ",i,j,k); /*存到文件*/
}
}
/* 利用穷举法背包问题
有不同价值,不同重量的物品n件,从中选一部分物品的选择方案.
要求选中物品的总重量不超过指定的限制重量,但选中的物品价值之和最大.
例:如果n=4,限制重量tw=7
4个物品的重量:1 2 3 4
4个物品的价值:4 3 2 1
则最佳选择: 1 1 1 0(1代表选择,0代表未选择)
则最大价值为:4+3+2=9,此时重量w=1+2+3=7<7
*/
#include "stdio.h"
#include "math.h"
#define MAX 100
/* 对n个物品,有2的n次方个选择组合,化为2进制的目的,
是让每一个二进制位1,0代表这个物品是否被选择*/
conversion(int n,int b[MAX])
{
int i;
for(i=0;i<MAX;i++)
{
b[i]=n%2;
n=n/2;
if(n==0) break;
}
}
main()
{
int i,j,n,b[MAX],temp[MAX];
float tw,maxv,w[MAX],v[MAX],temp_w,temp_v;
printf("please input n:"); scanf("%d",&n); /*输入物品数*/
printf("please input tw:"); scanf("%f",&tw); /*输入限制重量*/
for(i=0;i<n;i++)
{
printf("please input the values of w[%d]:",i);/*输入各物品的重量*/
scanf("%f",&w[i]);
}
for(i=0;i<n;i++)
{
printf("please input the values of v[%d]:",i);/*输入个物品的价值*/
scanf("%f",&v[i]);
}
maxv=0;
for(j=0;j<n;j++)
{
b[j]=0;
temp[j]=0;
}
for(i=0;i<pow(2,n);i++) /*穷举所有可能选择,找出最优选择*/
{
conversion(i,b);
temp_w=0;
temp_v=0;
for(j=0;j<n;j++) /*循环判断当前选择是否符合最优选择*/
if(b[j]==1)
{
temp_w=temp_w+w[j];
temp_v=temp_v+v[j];
}
if((temp_w<=tw)&&(temp_v>maxv))
{
maxv=temp_v;
for(j=0;j<n;j++)
temp[j]=b[j];
}
}
printf("the max values is %f: ",maxv); /*输出最大价值*/
printf("the selection is: ");
for(j=0;j<n;j++)
printf("%d",temp[j]); /*哪个物品被选择*/
}
/* 利用穷举法解决变量相等问题
1-6的6个整数组成一个3角形.每个边含顶点有3个数,要求三边相等的所有组合.
例:以下三边组合
a=1 b=6 c=3
c=3 d=2 e=5
e=5 f=4 a=1
*/
#include "stdio.h"
main()
{
int a,b,c,d,e,f;
for(a=1;a<=6;a++)
for(b=1;b<=6;b++)
{
if(b==a) continue;
for(c=1;c<=6;c++)
{
if((c==a)||(c==b)) continue;
for(d=1;d<=6;d++)
{
if((d==a) || (d==b) || (d==c)) continue;
for(e=1;e<=6;e++)
{
if((e==a)||(e==b)||(e==c)||(e==d)) continue;
f=21-(a+b+c+d+e);
if((a+b+c==c+d+e) && (a+b+c)==(a+e+f)) /*判断3个边是否相等*/
printf("a=%-4d b=%-4d c=%-4d d=%-4d e=%-4d f=%-4d ",a,b,c,d,e,f);
}
}
}
}
}