codeforce 1027 F. Session in BSU

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/albertluf/article/details/81975798

F. Session in BSU

time limit per test

4 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

Polycarp studies in Berland State University. Soon he will have to take his exam. He has to pass exactly nn exams.

For the each exam ii there are known two days: aiai — day of the first opportunity to pass the exam, bibi — day of the second opportunity to pass the exam (ai<biai<bi). Polycarp can pass at most one exam during each day. For each exam Polycarp chooses by himself which day he will pass this exam. He has to pass all the nn exams.

扫描二维码关注公众号,回复: 4178605 查看本文章

Polycarp wants to pass all the exams as soon as possible. Print the minimum index of day by which Polycarp can pass all the nn exams, or print -1 if he cannot pass all the exams at all.

Input

The first line of the input contains one integer nn (1≤n≤1061≤n≤106) — the number of exams.

The next nn lines contain two integers each: aiai and bibi (1≤ai<bi≤1091≤ai<bi≤109), where aiai is the number of day of the first passing the ii-th exam and bibi is the number of day of the second passing the ii-th exam.

Output

If Polycarp cannot pass all the nn exams, print -1. Otherwise print the minimum index of day by which Polycarp can do that.

思路:
每个a,b之间连一条边,最后形成多个连通图,
是一颗树的即edge==v+1,最大的点不选,若是
环即edge==v,则所有的点都选,若edge>v则-1。
代码:
#include<bits/stdc++.h>
using namespace std;
#define cherry main
const int maxn=2e6+10;
int par[maxn],num[maxn];
int a[maxn],b[maxn],c[maxn];
vector<int>G[maxn];
int Find(int x)
{
    if(x==par[x]) return x;
    return par[x]=Find(par[x]);
}
void unite(int x,int y)
{
    x=Find(x);y=Find(y);
    num[x]++;
    if(x!=y)
    {
        par[x]=y;
        num[y]+=num[x];
        num[x]=0;
    }
}
int cherry()
{
    for(int i=0;i<maxn;i++) par[i]=i;
    int n;scanf("%d",&n);
    int len=0;
    for(int i=1;i<=n;i++)
    {
        scanf("%d%d",&a[i],&b[i]);
        c[++len]=a[i];c[++len]=b[i];
    }
    sort(c+1,c+len+1);
    len=unique(c+1,c+len+1)-c-1;
    for(int i=1;i<=n;i++)
    {
        a[i]=upper_bound(c+1,c+len+1,a[i])-c-1;
        b[i]=upper_bound(c+1,c+len+1,b[i])-c-1;
    }
    for(int i=1;i<=n;i++) unite(a[i],b[i]);
    for(int i=1;i<=len;i++) G[Find(i)].push_back(i);
    bool bb=1;
    int ans=0;
    for(int i=1;i<=len;i++)
    {
        int SIZE=G[i].size();
        if(!SIZE) continue;
        sort(G[i].begin(),G[i].end());
        if(num[i]==SIZE) ans=max(ans,G[i][SIZE-1]);
        else if(num[i]==SIZE-1) ans=max(ans,G[i][SIZE-2]);
        else bb=0;
    }
    c[0]=-1;
    if(!bb) ans=0;
    printf("%d\n",c[ans]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/albertluf/article/details/81975798