Single Dogs-Sort 2

Insert picture description here
This question will time out with two for loops; it
is a thoughtful question;
there is a way to use three arrays to store the relationship between couples.
Look at the code and comments specifically, super detailed.

#include <bits/stdc++.h>
using namespace std;
#define MAXN 100010
int a[MAXN],b[MAXN],c[MAXN];//用c数组记录该人的对象需不需要'关爱'
int in[MAXN],out[MAXN];
int main()
{
    
    
    ios::sync_with_stdio(false);//加速
    int n;
    cin>>n;
    for(int i=0; i<n; i++)
    {
    
    
        int x,y;
        cin>>x>>y;//输入一对
        a[x]=y;//a数组保存每个人的对象
        a[y]=x;
        b[x]=b[y]=1;//b数组保存此人是否有对象
    }
    int m;
    cin>>m;
    for(int i=0; i<m; i++)
    {
    
    
        cin>>in[i];//in数组为输入的人
        if(b[in[i]])//如果这个人有对象
            c[a[in[i]]]=1;//则这个人的对象不需要关照
    }
    int k=0;
    for(int i=0; i<m; i++)
    {
    
    
        if(!c[in[i]])//需要关照的人
            out[k++]=in[i];//将需要关照的人放到out数组
    }
    sort(out,out+k);//排序
    cout<<k<<endl;//输出需要关照的人数
    for(int i=0; i<k; i++)
        printf("%05d%c",out[i],i==k-1?'\n':' ');//输出
    return 0;
}

Guess you like

Origin blog.csdn.net/rookie636/article/details/109035941