动态规划----国王建路问题( Constructing Roads In JGShining's Kingdom )

JGShining王国由2n个坐落在平行线上的城市组成,其中n个城市富有,另外n个城市贫穷,而正好n个富有城市可以为n个贫穷的城市提供资源,而且必须是一对一的,因为每个富有的城市所提供的资源各不相同,而每个贫穷的城市所需要的资源也各不相同。

HDU 1025 Constructing Roads In JGShinings Kingdom - 0 - 0


Input
Each test case will begin with a line containing an integer n(1 ≤ n ≤ 500,000). Then n lines follow. Each line contains two integers p and r which represents that Poor City p needs to import resources from Rich City r. Process to the end of file.
 


Output
For each test case, output the result in the form of sample. 
You should tell JGShining what's the maximal number of road(s) can be built. 
 


Sample Input
2
1 2
2 1
3
1 2
2 3
3 1
 


Sample Output
Case 1:
My king, at most 1 road can be built.


Case 2:
My king, at most 2 roads can be built.


做题思路:
对每一行进行排序,而排序的基准是第一列,因此p[a] = b,其中a代表第一列,而b代表第二列,从而转换为求解p数列的最长子序列问题。
最长子序列问题详解
代码如下:
#include <iostream>
using namespace std;
 
int p[500005], b[500005];
int n;
 
int bSearch(int num, int k)  
{  
    int low=1, high=k;  
    while(low<=high)  
    {  
        int mid=(low+high)/2;  
        if(num>=b[mid])  
            low=mid+1;  
        else   
            high=mid-1;  
    }  
    return low;  
}  
 
int LIS()
{
    int low = 1, high = n;
    int k = 1;
    b[1] = p[1];
    for(int i=2; i<=n; ++i)
    {
        if(p[i]>=b[k])
            b[++k] = p[i];
        else
        {
            int pos = bSearch(p[i], k);
            b[pos] = p[i];
        }
    }
    return k;
}
 
int main()
{
    int a, b;
    int nCases = 1;
    while(scanf("%d", &n) != EOF)
    {
        for(int i=1; i<=n; ++i)
        {
            scanf("%d %d", &a, &b);
            p[a] = b;
        }
        int ans = LIS();
        printf("Case %d:\nMy king, at most %d road", nCases++, ans);
        if(ans != 1) printf("s");
        printf(" can be built.\n\n");
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值