Codeforces 681D:Gifts by the List 思维

传送门

题目描述

一个家族有n个人,m种关系,之后行有 x y ,表示 x 是 y 的祖先,祖先具有传递性,然后有n个数,表示第 i 个人想把礼物送给 a[i],

你需要构造一张表这张表上的人代表收礼物的人,并且其他人送礼物是按表上的顺序找,找到的第一个祖先就是他要送礼的人,同时需要满足这个人

是他想送礼的人,如果存在这张表输出人数及编号,否则输出-1(题意中自己也算是自己的一个祖先)

分析

假如有一条链
A —> B -> C
那么,如果A如果要给C送礼,那么B一定要给C送礼,很简单,如果B要送礼,只能给B和C送礼物,如果给B送礼物,那么B就在C的前面,那么A就无法给C送礼,同理,如果B给B或者C送礼,那么A也只能跟B一样礼物

所以,我们可以判断出,一个节点,如果他要送礼,那么他的所有子孙的送礼情况都和这个点的情况一致,所以,我们只需要记录送礼给自己的节点答案即可

代码

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <cstring>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define _CRT_SECURE_NO_WARNINGS
#pragma GCC optimize("Ofast","unroll-loops","omit-frame-pointer","inline")
#pragma GCC option("arch=native","tune=native","no-zero-upper")
#pragma GCC target("avx2")
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
const int INF = 0x3f3f3f3f;
const int N = 1e5 + 10;
int h[N],e[N],ne[N],idx;
int in[N];
vector<int> ans;
int n,m;
int a[N];
bool flag;

void add(int x,int y){
    
    
    ne[idx] = h[x],e[idx] = y,h[x] = idx++;
}

void dfs(int x){
    
    
    for(int i = h[x];~i;i = ne[i]){
    
    
        int j = e[i];
        dfs(j);
        if(a[j] != j && a[x] != a[j]){
    
    
            flag = false;
        }
    }
    if(a[x] == x) ans.push_back(x);
}

int main(){
    
    
    flag = true;
    memset(h,-1,sizeof h);
    scanf("%d%d",&n,&m);
    while(m--){
    
    
        int x,y;
        scanf("%d%d",&x,&y);
        add(x,y);
        in[y]++;
    }
    for(int i = 1;i <= n;i++) scanf("%d",&a[i]);
    for(int i = 1;i <= n;i++)
        if(!in[i]){
    
    
            dfs(i);
        }
    if(!flag){
    
    
        puts("-1");
        return 0;
    }
    printf("%d\n",ans.size());
    for(auto t:ans) printf("%d\n",t);
    return 0;
}

/**
*  ┏┓   ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃       ┃
* ┃   ━   ┃ ++ + + +
*  ████━████+
*  ◥██◤ ◥██◤ +
* ┃   ┻   ┃
* ┃       ┃ + +
* ┗━┓   ┏━┛
*   ┃   ┃ + + + +Code is far away from  
*   ┃   ┃ + bug with the animal protecting
*   ┃    ┗━━━┓ 神兽保佑,代码无bug 
*   ┃        ┣┓
*    ┃        ┏┛
*     ┗┓┫┫
*    ┗┻┛ ┗┻┛+ + + +
*/


猜你喜欢

转载自blog.csdn.net/tlyzxc/article/details/112688887
今日推荐