题目
题解

#include<bits/stdc++.h>
using namespace std;
const int N=1002;
int P[N],C[N],c[N],p[N],cnt,cnt1,x,y,tag,i,n,tmp;
void ins(int *A,int k,int x){
    while (k && x<A[k-1]) A[k]=A[k-1],k--;
    A[k]=x;
}
int main(){
    scanf("%d",&n);
    for (i=0;i<n;i++){
        scanf("%d%d",&x,&y);
        if (x<=y) p[cnt]=x,c[cnt++]=y;
        else P[cnt1]=x,C[cnt1++]=y;
    }
    sort(P,P+cnt1);
    sort(C,C+cnt1);
    while (1){
        tmp=cnt1-1;
        while (tmp>=0 && P[tmp]<=C[tmp]) tmp--;
        if (tmp<0) break;
        tag=-1;
        for (i=0;i<cnt;i++)
            if (P[tmp]<=c[i] && p[i]<=C[tmp] && (tag==-1 || p[i]<p[tag])) tag=i;
        if (tag==-1)
            for (i=0;i<cnt;i++)
                if (P[tmp]<=c[i] && (tag==-1 || p[i]<p[tag])) tag=i;
        if (tag==-1){
            puts("-1");
            return 0;
        }
        ins(P,cnt1,p[tag]);
        ins(C,cnt1,c[tag]);
        cnt1++;cnt--;
        p[tag]=p[cnt];
        c[tag]=c[cnt];
    }
    printf("%d",cnt1);
}