有向直线2中值问题

#include "iostream"
#include "fstream"
using namespace std;

const int INF = 100000;
int w[100];
int d[100];
int total = 0;  
int n; 
int mincost = INF; //最小整体转移费用

int min(int a, int b)
{
    return a//计算如果在i, j位置设置服务机构,整体服务转移费用
int getcost(int i, int j)
{
    if(i>j)
        return 0;
    return total - w[i] * (d[j] - d[i]) - w[j] * (d[n+1] - d[j]);
}

//comp(1, n-1, 2, n)完成整个计算
void comp(int min1, int max1, int min2, int max2)
{
    int i, j, opt, optcost;
    if(min1 >= min2) 
        min2 = min1 + 1;
    if(max1 >= max2)
        max1 = max2 - 1;
    if((min1 > max1) || (min2 > max2))
        return;
    optcost = INF + 1;  //当前最小整体转移费用
    opt = 0;   //服务机构i的最优位置
    j = (min2 + max2) / 2;  //服务机构位置j
    for(i=min1; i<=min(max1, j-1); i++)  //另一个服务机构位置i,并且i
    {
        int cost = getcost(i, j);
        if(cost < optcost)  //更新当前最优解
        {
            optcost = cost;
            opt = i;
        }
    }
    if(optcost < mincost) //更新整体最优解
        mincost = optcost;  
    comp(min1, opt-1, min2, (min2+max2)/2-1);  //两个区间的左边
    comp(opt+1, max1, (min2+max2)/2+1, max2);  //两个区间的右边
}

int main()
{
    ifstream fin("two.txt");
    fin >> n;
    cout << "客户个数:" << n << endl;
    cout << "各个客户的服务需求量,转移费用分别为:\n";
    d[1] = 0;
    fin >> w[1]; cout << w[1] << " ";
    fin >> d[2]; cout << d[2] << endl;
    int cost, dist;
    for(int i=2; i<=n; i++)
    {
        fin >> cost; cout << cost << " ";
        fin >> dist; cout << dist << endl;
        w[i] = w[i-1] + cost; 
        d[i+1] = d[i] + dist;
        total += w[i] * dist;  //计算出总如果只在x0处设置服务机构,整体服务转移费用
    }
    comp(1, n-1, 2, n);
    cout << "最小整体转移费用为:" << mincost << endl;
    fin.close();
    return 0;
} 

有向直线2中值问题_第1张图片

你可能感兴趣的:(递归与分治)