codeforce 1027 F. Session in BSU
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.
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;
}