題面:
An architect wants to design a very high building. The building will consist of some floors, and eachfloor has a certain size. The size of a floor must be greater than the size of the floor immediatelyabove it. In addition, the designer (who is a fan of a famous Spanish football team) wants to paintthe building in blue and red, each floor a colour, and in such a way that the colours of two consecutivefloors are different.
To design the building the architect has n available floors, with their associated sizes and colours.All the available floors are of different sizes. The architect wants to design the highest possible buildingwith these restrictions, using the available floors.
Input
The input file consists of a first line with the number p of cases to solve. The first line of each casecontains the number of available floors. Then, the size and colour of each floor appear in one line.Each floor is represented with an integer between -999999 and 999999. There is no floor with size 0.Negative numbers represent red floors and positive numbers blue floors. The size of the floor is theabsolute value of the number. There are not two floors with the same size. The maximum number offloors for a problem is 500000.
Output
For each case the output will consist of a line with the number of floors of the highest building withthe mentioned conditions.
Sample Input
2
5
7
-2
6
9
-3
8
11
-9
2
5
18
17
-15
4
Sample Output
2
5
題面大意:
給定紅藍兩種木板要求,紅藍相間,且大小遞增,問最長能有多長。
解題:
算是貪心吧,排個序,能插就插,分別以兩個開頭,其實也可以合并成一次,看頭上能不能再加一個即可。
代碼:
#include <iostream>#include <algorithm>#include <vector>#include <cstdio>using namespace std;int red[500010],blue[500010];int main(){int t,n,tmp,cnt1,cnt2,maxx,cur,p1,p2;bool flag=0;scanf("%d",&t);while(t--) { cnt1=cnt2=maxx=0; scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%d",&tmp); if(tmp>0) red[cnt1++]=tmp; else blue[cnt2++]=-tmp; } sort(red,red+cnt1); sort(blue,blue+cnt2); tmp=0; cur=0; p1=p2=0; while(1) { flag=0; for(int i=p1;i<cnt1;i++) { if(red[i]>cur) { flag=1; p1=i+1; cur=red[i]; tmp++; break; } } if(!flag)break; flag=0; for(int i=p2;i<cnt2;i++) { if(blue[i]>cur) { flag=1; p2=i+1; cur=blue[i]; tmp++; break; } } if(!flag)break; } if(tmp>maxx) maxx=tmp; tmp=0; cur=0; p1=p2=0; while(1) { flag=0; for(int i=p2;i<cnt2;i++) { if(blue[i]>cur) { flag=1; p2=i+1; cur=blue[i]; tmp++; break; } } if(!flag)break; flag=0; for(int i=p1;i<cnt1;i++) { if(red[i]>cur) { flag=1; p1=i+1; cur=red[i]; tmp++; break; } } if(!flag)break; } if(tmp>maxx) maxx=tmp; printf("%d\n",maxx); }return 0;}