补题 C - CodeCoder vs TopForces Gym - 101142C

题目

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 TFi — ratings of the i-th citizen at CodeCoder and TopForces (1 ≤ CCi, TFi ≤ 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

解题思路

如果分别按照两种分数进行排序,就可以得到两个顺序,然后利用两个排序建边,利用dfs一次累计sum的值,就可以得到每个点所能战胜的人了

AC代码

#include
#include
#include
using namespace std;
const int maxn=100010;
struct node{
    int a,b,id;
}x[maxn],y[maxn];
int xid[maxn],yid[maxn],sum,ans[maxn];
bool vis[maxn];
bool cmp1(const node &a,const node &b){
    if(a.a==b.a){
        return a.b<b.b;
    }
    return a.a<b.a;
}
bool cmp2(const node &a,const node &b){
    if(a.b==b.b) return a.a<b.a;
    return a.b<b.b;
}

void dfs(int x){
    vis[x]=1;
    sum++;
    int idx=xid[x],idy =yid[x];
    if(!vis[idx]&&xid[idx]!=0) dfs(idx);//所有被搜索到的值都是已经被打败的值 
    if(!vis[idy]&&yid[idy]!=0) dfs(idy);
}


int main(){
    freopen("codecoder.in","r",stdin);
    freopen("codecoder.out","w",stdout);
    int n;
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>x[i].a>>x[i].b;
        x[i].id=i;
        y[i]=x[i];
    }
   
    sort(x+1,x+1+n,cmp1);//分别按照两种方式排序 
    sort(y+1,y+1+n,cmp2);
    for(int i=2;i<=n;i++){
        if(x[i].a>x[i-1].a) xid[x[i].id]=x[i-1].id;//建边 
        if(y[i].b>y[i-1].b) yid[y[i].id]=y[i-1].id;
        
    }
	for(int i=1;i<=n;i++){
		if(!vis[x[i].id]) dfs(x[i].id);
		if(!vis[y[i].id]) dfs(y[i].id);
		ans[x[i].id]=sum-1; 
	}
	for(int i=1;i<=n;i++)
        cout<<ans[i]<<endl;
}

你可能感兴趣的:(补题 C - CodeCoder vs TopForces Gym - 101142C)