首页 > 代码库 > CodeForces 645D Robot Rapping Results Report

CodeForces 645D Robot Rapping Results Report

二分,拓扑排序。

二分答案,然后进行拓扑排序检查,若某次发现存在两个或者两个以上入度为$0$的节点,那么不可行。

#pragma comment(linker, "/STACK:1024000000,1024000000")#include<cstdio>#include<cstring>#include<cmath>#include<algorithm>#include<vector>#include<map>#include<set>#include<queue>#include<stack>#include<iostream>using namespace std;typedef long long LL;const double pi=acos(-1.0),eps=1e-6;void File(){    freopen("D:\\in.txt","r",stdin);    freopen("D:\\out.txt","w",stdout);}template <class T>inline void read(T &x){    char c=getchar(); x=0;    while(!isdigit(c)) c=getchar();    while(isdigit(c)) {x=x*10+c-0; c=getchar();}}const int maxn=100010;int n,m,u[maxn],v[maxn];int h[maxn],sz,r[maxn];struct Edge{int u,v,nx;}e[maxn];void add(int a,int b){    e[sz].u=a; e[sz].v=b; e[sz].nx=h[a];    h[a]=sz++;}bool check(int x){    memset(h,-1,sizeof h); sz=0;    memset(r,0,sizeof r);    for(int i=1;i<=x;i++) add(u[i],v[i]),r[v[i]]++;    queue<int>Q;    int num=0; for(int i=1;i<=n;i++) if(r[i]==0) Q.push(i),num++;        if(num!=1) return 0;    while(!Q.empty())    {        int top=Q.front(); Q.pop();        num=0;        for(int i=h[top];i!=-1;i=e[i].nx)        {            r[e[i].v]--;            if(r[e[i].v]==0)            {                num++;                Q.push(e[i].v);            }        }        if(num>1) return 0;    }    return 1;}int main(){    scanf("%d%d",&n,&m);    for(int i=1;i<=m;i++) scanf("%d%d",&u[i],&v[i]);    check(4);    int L=1,R=m,ans=-1;    while(L<=R)    {        int m=(L+R)/2;        if(check(m)) ans=m,R=m-1;        else L=m+1;    }    printf("%d\n",ans);    return 0;}

 

CodeForces 645D Robot Rapping Results Report