33,008
社区成员
发帖
与我相关
我的任务
分享
/*里面的表格代表的是有 N个村庄,表格列出了每个村庄到其他村庄的距离
From Village 1 Village 2 Village 3 Village 4 Village 5 Village 6
Village 1 0 10 20 30 30 20
Village 2 10 0 25 35 20 10
Village 3 20 25 0 15 30 20
Village 4 30 35 15 0 15 25
Village 5 30 20 30 15 0 14
Village 6 20 10 20 25 14 0
现在想造消防站,求最少需要造几个消防站,这样可以让任意村庄都至少有一个消防站可以在15分钟内到达*/
#include <iostream>
#include <vector>
using namespace std;
#define M 6 //N个村庄
int threshold = 15;//15分钟内到达
int a[M][M] = { 0,10,20,30,30,20,\
10,0 ,25,35,20,10,\
20,25,0 ,15,30,20,\
30,35,15,0 ,15,25,\
30,20,30,15,0 ,14,\
20,10,20,25,14,0};
struct TValid //第num个村庄有消防站,则15分钟内可以到达validVect内的村庄
{
int num;
vector<int> validVect;
};
TValid valid[M];
int checked[M] = {0};//第i个消防站放在checked[i]村庄中
int result[M] = {0};//最终结果
int minCount = M;//保存最少需要造几个消防站
int countExist(int n)
{
int bitChecked[M] = {0};
int res = 0;
for (int i = 0; i < n; i++)
{
if (bitChecked[checked[i]] == 0)
{
res += 1;
bitChecked[checked[i]] = 1;
}
}
return res;
}
void check(int n)
{
if (n > M-1)
{
int curCount = countExist(M);
if (curCount < minCount)
{
minCount = curCount;
for (int i = 0; i < M; i++)
{
result[i] = checked[i];
}
}
return;
}
TValid curValid = valid[n];
vector<int>::iterator it;
for (it = curValid.validVect.begin(); it != curValid.validVect.end();++it)
{
checked[n] = *it;
if (countExist(n) >= minCount)
continue;
check(n+1);
}
}
void printResult()//打印结果
{
cout<<"最少需要造 "<<minCount<<" 个消防站"<<endl;
int bitChecked[M] = {0};
cout<<"分别在:";
for (int i = 0; i < M; i++)
{
if (bitChecked[result[i]] == 0)
{
bitChecked[result[i]] = 1;
cout<<"Village "<<result[i]+1<<" ";
}
}
cout<<endl;
}
int main()
{
for (int i = 0; i < M; i++)
{
valid[i].num = i;
for (int j = 0; j < M; j++)
{
if(a[i][j] <= threshold)
{
valid[i].validVect.push_back (j);
}
}
}
check(0);
printResult();
return 0;
}
#include <iostream>
#include <algorithm>
#include <vector>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define M 4
int a[M][M] = {14,5,8,7,\
2,12,6,5,\
7,8,3,9,\
2,4,6,10};
int b[M];
int compare(int i,int j)
{
if (a[i][i] + a[j][j] < a[i][j] + a[j][i])
return 0;
else
return 1;
}
void exchange(int m,int n)
{
int temp[M];
for (int i = 0; i < M; i++)
{
temp[i] = a[m][i];
}
for (int i = 0; i < M; i++)
{
a[m][i] = a[n][i];
}
for (int i = 0; i < M; i++)
{
a[n][i] = temp[i];
}
int t = b[m];
b[m] = b[n];
b[n] = t;
}
int main () {
for (int i = 0; i < M; i++)
{
b[i] = i;
}
for (int i = 0; i < M; i++)
{
for (int j = i+1; j < M; j++)
{
if (compare(i,j) > 0)
{
exchange(i,j);
}
}
}
for (int i = 0; i < M; i++)
{
cout<<"Machine "<<b[i]+1<<" execute JOB "<<i+1;
cout<<endl;
}
int total = 0;
cout<<"Total: ";
for (int i = 0; i < M; i++)
{
total += a[i][i];
cout<<a[i][i]<<" ";
}
cout<<"="<<total;
return 0;
}