1. 程式人生 > >洛谷 2782友好城市

洛谷 2782友好城市

情況 city not sin 一個空格 成了 ios namespace cit

題目背景

題目描述

有一條橫貫東西的大河,河有筆直的南北兩岸,岸上各有位置各不相同的N個城市。北岸的每個城市有且僅有一個友好城市在南岸,而且不同城市的友好城市不相同。沒對友好城市都向政府申請在河上開辟一條直線航道連接兩個城市,但是由於河上霧太大,政府決定避免任意兩條航道交叉,以避免事故。編程幫助政府做出一些批準和拒絕申請的決定,使得在保證任意兩條航道不相交的情況下,被批準的申請盡量多。

輸入輸出格式

輸入格式:

第1行,一個整數N(1<=N<=5000),表示城市數。

第2行到第n+1行,每行兩個整數,中間用一個空格隔開,分別表示南岸和北岸的一對友好城市的坐標。(0<=xi<=10000)

輸出格式:

僅一行,輸出一個整數,表示政府所能批準的最多申請數。

輸入輸出樣例

輸入樣例#1:
7
22 4
2 6
10 3
15 12
9 8
17 17
4 2
輸出樣例#1:
4

說明

1<=N<=5000,0<=xi<=10000

思路:很明顯這是一道dp問題。按照南岸城市大小排序,要想不交叉,下一組友好城市的北岸一定比上一組的,所以這就轉換成了求最大上升子序列問題

代碼:

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 using
namespace std; 5 struct city{ 6 int south; 7 int noth; 8 }citys[5001]; 9 int f[5001]; 10 int n,ans; 11 int cmp(const city &a,const city &b) 12 { 13 return a.south<b.south; 14 } 15 void dp() 16 { 17 for(int i=1;i<=n;i++) 18 for(int j=1;j<i;j++) 19 if
(citys[j].noth<citys[i].noth) 20 f[i]=max(f[i],f[j]+1); 21 } 22 int main() 23 { 24 cin>>n; 25 for(int i=1;i<=n;i++) 26 { 27 cin>>citys[i].south>>citys[i].noth; 28 f[i]=1; 29 } 30 sort(citys+1,citys+1+n,cmp); 31 dp(); 32 for(int i=1;i<=n;i++) 33 ans=max(ans,f[i]); 34 cout<<ans; 35 return 0; 36 }

洛谷 2782友好城市