//
分别以不同起点开始进行以当前最优的策略选择,直到依次遍历所有的开始点
#include
<stdio
.h
>
#include
<stdlib
.h
>
#define
MAXSIZE 60
bool
HasExist(int Exist
[],int len
,int flag
){
for (int i
= 0; i
< len
; i
++)
{
if(Exist
[i
]==flag
)
return true;
}
return false;
}
void GreedyAL(int weight
[],int Value
[],int len
,int MaxWeigh
){
int RValue
[MAXSIZE];
int RWeight
[MAXSIZE];
int Exist
[MAXSIZE][MAXSIZE];
int flag
= 0;
for (int k
= 0; k
< len
; k
++)
{
flag
= 0;
RValue
[k
] = Value
[k
];
RWeight
[k
] = weight
[k
];
Exist
[k
][flag
++] = k
;
for(int i
= 0;i
<len
;i
++){
int max
= -1;
int fl
= -1;
for (int j
= 0; j
< len
; j
++)
{
if(weight
[j
]+RWeight
[k
]<=MaxWeigh
&&k
!=j
){
if(HasExist(Exist
[k
],flag
,j
)){
continue;
}else{
if(Value
[j
]>max
)
{
max
= Value
[j
];
fl
= j
;
}
}
}
}
if(RWeight
[k
]>=MaxWeigh
||fl
==-1)
{
Exist
[k
][flag
] = -1;
break;
}
RWeight
[k
]+=weight
[fl
];
RValue
[k
] += max
;
Exist
[k
][flag
++] = fl
;
}
}
int max
= 0;
for (int i
= 1; i
< len
; i
++)
{
if(RValue
[max
]<RValue
[i
]){
max
= i
;
}
}
for(int i
= 0 ;i
< len
;i
++){
printf("Start in %d-th Goods: ",(i
+1));
for (int j
= 0;Exist
[i
][j
] != -1; j
++)
{
printf("%d ",Exist
[i
][j
]);
}
printf("\nMaxValue : %d MaxWeigh : %d\n\n",RValue
[i
],RWeight
[i
]);
}
printf("MaxValue : %d MaxWeigh : %d\nBEST SUCCESSION : ",RValue
[max
],RWeight
[max
]);
for (int i
= 0; Exist
[max
][i
]!=-1; i
++)
{
printf("%d ",Exist
[max
][i
]);
}
printf("\n");
}
int
main(){
int Weigh
[]={35,30,60,50,40,10,25};
int Value
[]={10,40,30,50,35,40,30};
int len
= sizeof(Value
)/sizeof(int
);
GreedyAL(Weigh
,Value
,len
,155);
system("pause");
return 0;
}
转载请注明原文地址:https://tech.qufami.com/read-18065.html