算法——分治法 练习

问题一:

Description

n 个元素的集合{1,2,., n }可以划分为若干个非空子集。例如,当n=4 时,集合{1,2, 3,4}可以划分为15 个不同的非空子集如下:

{{1},{2},{3},{4}},

{{1,3},{2},{4}},

{{1,4},{2},{3}},

{{2,3},{1},{4}},

{{2,4},{1},{3}},

{{3,4},{1},{2}},

{{1,2},{3,4}},

{{1,3},{2,4}},

{{1,4},{2,3}},

{{1,2,3},{4}},

{{1,2,4},{3}},

{{1,3,4},{2}},

{{2,3,4},{1}},

{{1,2,3,4}}

给定正整数n和m,利用分治算法计算出n 个元素的集合{1,2,., n }可以划分为多少个不同的由m个非空子集组成的集合。

Input

元素个数n和非空子集数m。

Output

计算出共有多少个不同的由m 个非空子集组成的集合。

Sample Input

4 2

Sample Output

7


#include<iostream>
using namespace std;

int f(int n,int m)
{
    if(m==1||n==m)
        return 1;
    else
        return f(n-1,m-1)+f(n-1,m)*m;
}

int main()
{
    int m,n,sum;
    cin>>n>>m;
    sum=f(n,m);
    cout<<sum;
    return 0;
}


问题二:

Description

某石油公司计划建造一条由东向西的主输油管道。该管道要穿过一个有n 口油井的油田。从每口油井都要有一条输油管道沿最短路经(或南或北)与主管道相连。如果给定n 口油井的位置,即它们的x 坐标(东西向)和y 坐标(南北向),应如何确定主管道的最优位置, 即使各油井到主管道之间的输油管道长度总和最小的位置?给定n 口油井的位置,编程计算各油井到主管道之间的输油管道最小长度总和。

Input

首行为油井数量n,其他行为每口油井的横坐标xi,纵坐标yi

Output

油井到主管道之间的输油管道最小长度总和。

Sample Input

5
1 2
3 5
3 7
3 4
2 7

Sample Output

8


#include<iostream>
using namespace std;

void MaxMin(int i,int j,int& max,int& min,int l[])
{
    int min1,max1;
    if(i==j) min=max=l[i];
    else if(i==j-1)
    {
        if(l[i]<l[j])
        {
            max=l[j];min=l[i];
        }
        else
        {
            max=l[i];min=l[j];
        }
    }
    else
    {
        int m=(i+j)/2;
        MaxMin(i,m,max,min,l);
        MaxMin(m+1,j,max1,min1,l);
        if(max<max1) max=max1;
        if(min>min1) min=min1;
    }
}

int main()
{
    int x[20],y[20];
    int s,p,q,t,sum=0;
    int max,min,min1=1000;
    cin>>s;
    for(int k=0;k<s;k++)
    {
        cin>>x[k]>>y[k];
    }
    MaxMin(0,s-1,max,min,y);


        for(q=min;q<=max;q++)
        {
            for(p=0;p<s;p++)
            {
                t=q-y[p];
                if(t<0) t=-t;
                sum=sum+t;
            }
            if(sum<min1) min1=sum;
            sum=0;
        }
        cout<<min1;
        return 0;

}



问题三:

Description

给定一整数数组A=(A1,A2,…An), 若i<j且Ai>Aj,则<I,j>就为一个逆序对。1<=n<=30000。例如数组(3,1,4,5,2)的逆序对有<3,1>,<3,2>,<4,2>,<5,2>

Input

n和A数组

Output

逆序对数目

Sample Input

5
3 1 4 5 2

Sample Output

4


#include<iostream>
using namespace std;

int main()
{
    int n;
    int i,j,sum=0;
    int a[30000];
    cin>>n;
    for(i=0;i<n;i++)
    {
        cin>>a[i];
    }
    for(i=0;i<n;i++)
    {
        for(j=i+1;j<n;j++)
        {
            if(a[i]>a[j]) sum++;
        }
    }
    cout<<sum<<endl;
    return 0;
}
(不是分治法)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值