Topic Link: Portal
The main idea: a family has n individuals, m relationships, followed by X Y, indicating that X is the ancestor of Y, the ancestor has transitivity, and then there are n number, indicating that I personally want to give the gift to A[i],
You need to construct a table. The person on the watch represents the person receiving the gift, and the other person presents the gifts in the order of the table, the first ancestor to find is the person he wants to give gifts, and he needs to meet this person.
He is the one who wants to give gifts, if there is this table output number and number, otherwise output 1 (the question oneself also is an ancestor of oneself)
Topic idea: We want to draw a conclusion from the test instructions: a diagram
A->b->c->d if a want to give gifts to D, then b,c must give D gift, otherwise contradictory.
Proof: If a to D send, B to C, the table B must find the first ancestor is C to give C gift, so C in the table should be more than D before, when a found the first ancestor should be C,
Then a should also give gifts to C, and conditions contradiction, get proof.
Second conclusion, if there is such a table, then the table only want to give their own gifts. Because a person gives gifts to his ancestors, all the descendants of his ancestors will give his ancestors a gift (the first conclusion above)
Then we just need to save our ancestors.
1#include <iostream>2#include <cstdio>3#include <cstdlib>4#include <cmath>5#include <algorithm>6#include <cstring>7#include <stack>8#include <cctype>9#include <queue>Ten#include <string> One#include <vector> A#include <Set> -#include <map> -#include <climits> the #defineLson Root<<1,l,mid - #defineRson Root<<1|1,mid+1,r - #defineFi first - #defineSe Second + #definePing (x, y) ((x-y) * (x-y)) - #defineMST (x, y) memset (x,y,sizeof (x)) + #defineMCP (x, y) memcpy (x,y,sizeof (y)) A using namespacestd; at #defineGamma 0.5772156649015328606065120 - #defineMOD 1000000007 - #defineINF 0x3f3f3f3f - #defineN 100005 - #defineMAXN 1005 -typedef pair<int,int>PII; intypedefLong LongLL; - to intA[n]; + int inch[n],ans[n],cnt; - intn,m,k; the structnode{ * intTo,next; $ }node[n];Panax Notoginseng inthead[n],hcnt; -InlinevoidAddintXinty) { thenode[hcnt].to=y;node[hcnt].next=Head[x]; +head[x]=hcnt++;++inch[y]; A } the voidDfsintx) { + for(intI=head[x];~i;i=Node[i].next) { - intE=node[i].to; $ DFS (e); $ if(a[e]!=e&&a[x]!=A[e]) { -Exit0*printf ("-1\n")); - } the } - if(a[x]==x) {ans[cnt++]=x;}Wuyi } the intMain () { - inti,j,group,x,y; WuMST (head,-1); hcnt=0; -scanf"%d%d",&n,&m); About for(i=1; i<=m;++i) { $scanf"%d%d",&x,&y); - Add (x, y); - } - for(i=1; i<=n;++i) {scanf ("%d",&a[i]);} A for(i=1; i<=n;++i) { + if(!inch[i]) DFS (i); the } -printf"%d\n", CNT); $ for(i=0; i<cnt;++i) theprintf"%d\n", Ans[i]); the return 0; the}
Codeforces 681D (Gifts by the List)