Sister cities of the longest ascending subsequence model

Related topics :

Longest ascending subsequence

Kaito Kidd's Hang Glider

Climbing

Missile interception

Title description:

Palmia has a large river that runs from east to west. The river has straight north and south banks, and there are N cities with different locations on each bank.

Each city on the North Bank has one and only one sister city on the South Bank, and the sister cities of different cities are different.

Each pair of sister cities applied to the government to open a straight waterway on the river to connect the two cities, but due to the fog on the river, the government decided to avoid any two waterway crossings to avoid accidents.

Programming helps the government make some decisions to approve and reject applications, so that as many applications as possible are approved while ensuring that any two routes do not intersect.
Input format

In the first line, an integer N represents the number of cities.

From line 2 to line n+1, each line contains two integers, separated by a space, indicating the coordinates of a pair of sister cities on the south bank and the north bank.
Output format

Only one line, output an integer, indicating the maximum number of applications that the government can approve.
data range

1≤N≤5000,
0≤xi≤10000

Input sample :

7
22 4
2 6
10 3
15 12
9 8
17 17
4 2

Sample output:

4

Ideas :

两条航线不能相交,相交的条件是a1>a2&&b1<b2(a1是航道1,b2是
航道2)要想不相交只需把航道a1按顺序排,再找排序后a1对应的航道b2
的最长子序列;

Code


import java.util.Arrays;
import java.util.Scanner;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner input=new Scanner(System.in);
        int N=input.nextInt();
        PII arr[]=new PII[N+1];
        for(int i=1;i<=N;i++){
    
    
            int first=input.nextInt();
            int second=input.nextInt();
            arr[i]=new PII(first,second);
        }
        Arrays.sort(arr,1,N+1);
        int []dp=new int[N+1];
        int res=1;
        for(int i=1;i<=N;i++){
    
    
            dp[i]=1;
            for(int j=1;j<i;j++){
    
    
                if(arr[i].second>arr[j].second){
    
    
                    dp[i]=Math.max(dp[j]+1,dp[i]);
                    res=Math.max(dp[i],res);
                }
            }
        }
        System.out.println(res);

    }
}
class  PII implements Comparable<PII>{
    
    
    public   int first;
    public  int second;
    public PII(int first,int second){
    
    
        this.first=first;
        this.second=second;
    }
    public int compareTo(PII o){
    
    
        return  Integer.compare(this.first,o.first);
    }

}

Guess you like

Origin blog.csdn.net/qq_44844588/article/details/108339318