Problem C. CodeCoder vs TopForces
Competitive programming is very popular in Byteland. In fact, every Bytelandian citizen is registered
at two programming sites — CodeCoder and TopForces. Each site maintains its own proprietary rating
system. Each citizen has a unique integer rating at each site that approximates their skill. Greater rating
corresponds to better skill.
People of Byteland are naturally optimistic. Citizen A thinks that he has a chance to beat citizen B in
a programming competition if there exists a sequence of Bytelandian citizens A = P0, P1, . . . , Pk = B for
some k ≥ 1 such that for each i (0 ≤ i < k), Pi has higher rating than Pi+1 at one or both sites.
Each Bytelandian citizen wants to know how many other citizens they can possibly beat in a programming
competition.
Input
The first line of the input contains an integer n — the number of citizens (1 ≤ n ≤ 100 000). The
following n lines contain information about ratings. The i-th of them contains two integers CCi and
T Fi — ratings of the i-th citizen at CodeCoder and TopForces (1 ≤ CCi
, T Fi ≤ 106
). All the ratings at
each site are distinct.
Output
For each citizen i output an integer bi — how many other citizens they can possibly beat in a programming
competition. Each bi should be printed in a separate line, in the order the citizens are given in the input.
Example
codecoder.in
4
2 3
3 2
1 1
4 5
codecoder.out
2
2
0
3
一、原题地址
二、大致题意
一群人有两个能力值,如果一个人其中的一项能力值大于另外一个人的,那么就可以击败对方,并且这里需要注意如果选手A能击败B,选手B能击败C,那么A就能击败C。
询问每个选手能击败的人数。
三、大致思路
难点就在于击败对手是可以传递的,很简单就能想到n^2复杂度去建边然后跑深搜,但是复杂度是不能接受的。
其实注意到,当我们把选手按照第一个能力值升序排序后,第i+1的选手一定能击败第 i 个选手,所以我们依次O(n)地连边,这样就保证了胜利可以传递,且我们已经建立了第一个能力值的胜利关系。同理再按照第二个能力值升序排序再建好边。
现在问题就变成了统计从一点出发所能到达的点的个数,显然这是DFS可以解决的,但是不可能从每个点都重新出发重跑DFS。
注意到我们之前排序好的点,此时是按照第二能力值排序的,如果我们只考虑第二能力值,也就是说每个当前的点 i 在跑搜索时是一定会有向 i-1 的点跑的趋势,形象的理解就像是在向图的内侧跑,那么按照第二能力顺序跑深搜,是可以把图从中心向外围丰满的。也就是说只需要记录一个全局的cnt,那么对于已经标记过的点一定是属于之前的块而不会错乱顺序。
口胡感觉不是太能懂,还是看代码思考吧。感觉和拓扑的想法很像,拓扑是一点一点去掉外围的点,而这里则是从中间一点一点向外围增加。
四、代码
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
#include<cmath>
#include<iostream>
#include<deque>
#include<cstring>
#include<vector>
using namespace std;
#define LL long long
const int inf=0x3f3f3f3f;
const int maxn=1e5+5;
int n;
struct Node
{
int c,f,id;
}a[maxn];
bool cmp1(Node xx,Node yy)
{
return xx.c<yy.c;
}
bool cmp2(Node xx,Node yy)
{
return xx.f<yy.f;
}
vector<int>e[maxn];
bool vis[maxn];
int cnt,ans[maxn];
void DFS(int nx)
{
cnt++;
vis[nx]=true;
for(int i=0;i<e[nx].size();i++)
{
int to =e[nx][i];
if(!vis[to])
{
DFS(to);
}
}
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d %d",&a[i].c,&a[i].f);
a[i].id=i;
vis[i]=false;
}
sort(a+1,a+1+n,cmp1);
for(int i=2;i<=n;i++)e[a[i].id].push_back(a[i-1].id);
sort(a+1,a+1+n,cmp2);
for(int i=2;i<=n;i++)e[a[i].id].push_back(a[i-1].id);
cnt=0;
for(int i=1;i<=n;i++)
{
if(!vis[a[i].id])
{
DFS(a[i].id);
}
ans[a[i].id]=cnt-1;
}
for(int i=1;i<=n;i++)
{
printf("%d\n",ans[i]);
}
}