Language: Default Popular Cows
Description Every cow‘s dream is to become the most popular cow in the herd. In a herd of N (1 <= N <= 10,000) cows, you are given up to M (1 <= M <= 50,000) ordered pairs of the form (A, B) that tell you that cow A thinks that cow B is popular. Since popularity is transitive, popular, even if this is not explicitly specified by an ordered pair in the input. Your task is to compute the number of cows that are considered popular by every other cow. Input * Line 1: Two space-separated integers, N and M * Lines 2..1+M: Two space-separated numbers A and B, meaning that A thinks B is popular. Output * Line 1: A single integer that is the number of cows who are considered popular by every other cow. Sample Input 3 3 1 2 2 1 2 3 Sample Output 1 Hint Cow 3 is the only cow of high popularity. Source |
题意: n头牛相互羡慕,可以传递羡慕,问被所有牛羡慕的牛的最大数目
思路:
tarjan缩点,把不同的点规划到一个强联通分支,最后判断强连通分支出度为0的点是否唯一,唯一则有解,答案是该强连通分支的点的数目,否者无解
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cmath> #include<queue> #include<stack> #include<vector> #include<set> #include<map> #define L(x) (x<<1) #define R(x) (x<<1|1) #define MID(x,y) ((x+y)>>1) #define eps 1e-8 typedef __int64 ll; #define FRE(i,a,b) for(i = a; i <= b; i++) #define mem(t, v) memset ((t) , v, sizeof(t)) #define sf(n) scanf("%d", &n) #define sff(a,b) scanf("%d %d", &a, &b) #define sfff(a,b,c) scanf("%d %d %d", &a, &b, &c) #define pf printf #define bug pf("Hi\n") using namespace std; #define N 10024 int head[N],low[N],time[N],e_num,tim_num; int n,m,ans,instack[N],vis[N],type[N],out[N]; struct stud{ int to,next; }e[N*10]; stack<int>q; inline void add(int u,int v) { e[e_num].to=v; e[e_num].next=head[u]; head[u]=e_num++; } void tarjan(int x) { int i,j; q.push(x); instack[x]=1; time[x]=low[x]=++tim_num; for(i=head[x];i!=-1;i=e[i].next) { int to=e[i].to; if(time[to]==0) { tarjan(to); if(low[x]>low[to]) low[x]=low[to]; } else if(instack[to]&&low[x]>time[to]) low[x]=time[to]; } if(low[x]==time[x]) { ans++; do{ j=q.top(); q.pop(); instack[j]=0; type[j]=ans; //标记j 属于第几个联通分支 vis[ans]++; //这个联通分支的点+1 // printf("%d ans=%d\n",j,ans); }while(j!=x); } } void solve() { int i,j; mem(time,0); mem(instack,0); mem(out,0); mem(vis,0); ans=tim_num=0; for(i=1;i<=n;i++) if(time[i]==0) tarjan(i); for(i=1;i<=n;i++) for(j=head[i];j!=-1;j=e[j].next) { int to=e[j].to; if(type[i]!=type[to]) { out[type[i]]=1; //标记有出度的联通分支 } } int t=0,pos; for(i=1;i<=ans;i++) //一共有ans个联通分支,取出其中 if(out[i]==0) { t++; pos=i; if(t>1) break; } //如果出度为0的联通分支只有一个,那么这个联通分支的个数就是答案, //否则,无解 if(t==1) printf("%d\n",vis[pos]); else printf("0\n"); } int main() { int i,j; scanf("%d%d",&n,&m); { int u,v; e_num=0; mem(head,-1); while(m--) { sff(u,v); add(u,v); } solve(); } return 0; }