贪心法
1.单源最短路径问题
#include<stdio.h>
#include<iostream>
#include<cmath>
using namespace std;
#define M 1000
int Cost[20][20];
int n;
int Distance[20];
bool s[20];
int pr[20];
int source;
void Dijkstra()
{
int i, j;
//初始化
for(i=1; i<=n; i++)
{
Distance[i] = Cost[source][i];
s[i] = false;
if(Distance[i]==M)
{
pr[i]=0;
}
else
{
pr[i]=source;
}
}
Distance[source] = 0;
s[source] = true;
for(i=1; i < n; i++)
{//每循环一次,求得一个最短路径
int temp=M;
int u=source;
for (j=1; j <= n; j++) //求离出发点最近的顶点
if((!s[j]) && Distance[j]<temp)
{
temp = Distance [j];
u = j;
}
s[u] =true;
for(j=1; j<=n; j++) //修改递增路径序列(集合)
{
if((!s[j])&& Cost[u][j]<M)
{ //对还未求得最短路径的顶点
//求出由最近的顶点 直达各顶点的距离
int newdis = Distance[u] +Cost[u][j];
// 如果新的路径更短,就替换掉原路径
if(Distance[j] > newdis)
{
Distance[j] = newdis;
pr[j] = u;
}
}
}
}
}
void Traceback(int i)
{
if(source == i)
{
printf("%d",i);
return;
}
Traceback(pr[i]);
cout<<"->"<<i;
}
int main()
{
cout<<"请输入个数:"<<endl;
cin>>n;
int i,j;
source = 1;//源点为1
cout<<"请输入代价矩阵:"<<endl;
for(i=1; i<=n; i++)
{
for(j=1; j<=n; j++)
{
scanf("%d",&Cost[i][j]);
}
}
Dijkstra();
for(i=2; i<=n; i++)
{
printf("从1到点%d的最短路径长度:%d,路径:",i,Distance[i]);
Traceback(i);
printf("\n");
}
system("pause");
return 0;
}
2.多机调度问题
假定有7个独立作业,所需处理时间分别为{2,14,4,16,6,5,3},由三台机器M1,M2,M3加工。按照贪心算法所需总加工时间为17.
#include<stdio.h>
#include<algorithm>
#include<iostream>
using namespace std;
struct work
{
int time;
int num;
}homework[20];
void multimachine(work homework[20],int n,int m)
{
int h[20][20]={0};
int d[20];
int real[20];
int sum,i,j,k;
for(i=1;i<=m;i++)
{
h[i][1]=homework[i].num;
real[i]=1;
d[i]=homework[i].time;
}
for(i=m+1;i<=n;i++)
{
for(j=1,k=2;k<=m;k++)
if(d[k]<d[j])
j=k;
real[j]++;
h[j][real[j]]=homework[i].num;
d[j]=d[j]+homework[i].time;
}
for(i=1;i<=m;i++)
{
printf("机器%d处理:",i);
for(j=1;h[i][j]>0;j++)
{
printf("作业%d ",h[i][j]);
}
printf("\n");
}
for(i=1;i<=m;i++)
{
sum=d[i]>d[i+1]?d[i]:d[i+1];
}
printf("完成时间为:%d\n",sum);
}
bool cmp(work a,work b)
{
return a.time>b.time;
}
int main()
{
int m;
printf("机器个数:");
cin>>m;
int n;
printf("作业个数:");
cin>>n;
printf("各作业完成所需时间:\n");
int i;
for(i=1;i<=n;i++)
{
scanf("%d",&homework[i].time);
homework[i].num=i;
}
sort(homework+1,homework+10,cmp);
multimachine(homework,n,m);
system("pause");
return 0;
}