- 论坛徽章:
- 0
|
求教一算法(阿里巴巴进山洞取宝)
时间仓促,没来得及校对,简单测试了一下,似乎没问题。
权做抛砖引玉。
- #include <stdio.h>;
- #define jewel_count 7 /* 财宝个数 */
- #define MAXWEIGHT 6 /* 最大承重 */
- int bag[jewel_count];
- int got_count=0;
-
- int best_bag[jewel_count];
- int best_got_count=0;
- int best_value=0;
-
- struct jewel_type
- {
- int p; /* Cost */
- int w; /* Weight */
- };
- struct jewel_type jewel[jewel_count];
- void
- init_hole()
- {
- int i;
- int c;
- FILE *fp;
- fp=fopen("/dev/urandom","r");
- for (i=0;i<jewel_count;i++) {
- c=fgetc(fp)%5+1; /* 重量和价值取1-5随机值 */
- jewel[i].p=c;
- c=fgetc(fp)%5+1;
- jewel[i].w=c;
- }
- fclose(fp);
- }
- int
- exists(int n)
- {
- int i;
- for (i=0;i<got_count;i++) {
- if (bag[i]==n) return 1;
- }
- return(0);
- }
- void
- output()
- {
- int i;
- for (i=0;i<got_count;i++) {
- printf("%d ",bag[i]);
- }
- printf("\n");
- }
- int
- weight()
- {
- int i,sum=0;
- for (i=0;i<got_count;i++) {
- sum+=jewel[bag[i]].w;
- }
- return sum;
- }
- int
- value()
- {
- int i,sum=0;
- for (i=0;i<got_count;i++) {
- sum+=jewel[bag[i]].p;
- }
- return sum;
- }
- void
- refresh()
- {
- int i;
- if (value()>;=best_value) {
- for (i=0;i<got_count;i++) {
- best_bag[i]=bag[i];
- }
- best_got_count=got_count;
- best_value=value();
- }
- }
- void
- resolv()
- {
- int i,temp;
- int tempweight;
- if ((tempweight=weight())<=MAXWEIGHT) {
- refresh();
- output();
- }
- if (tempweight>;MAXWEIGHT) {
- return;
- }
- for (i=got_count;weight()<=MAXWEIGHT && i<jewel_count;i++) {
- if (exists(i)==0) {
- bag[got_count++]=i;
- resolv();
- got_count--;
- }
- }
- }
- void
- outputbest()
- {
- int i,weight=0,value=0;
- printf("Best answer is:");
- for (i=0;i<best_got_count;i++) {
- printf("%d ",best_bag[i]);
- weight+=jewel[best_bag[i]].w;
- value+=jewel[best_bag[i]].p;
- }
- printf("\nvalue is: %d\tweight is: %d\n",value,weight);
- }
- main()
- {
- int i;
- init_hole();
- for (i=0;i<jewel_count;i++) {
- printf("Jewel No%d: \t cost=%d \tweight=%d\n",i,jewel[i].p,jewel[i].w);
- }
- resolv();
- outputbest();
- }
复制代码 |
|