CodeForces 645D Robot Rapping Results Report(二分+拓扑排序)

来源:互联网 发布:用淘宝联盟被发现了 编辑:程序博客网 时间:2024/05/17 23:48

题意:有很多机器人,其中如果1号打败2号,2号打败3号,那么1号也可以打败3号,给你m场比赛的结果,问最少需要知道前几场就可以确定机器人的排名

思路:二分答案,然后拓扑排序看看是否成一条直线即可


#include <cstdio>#include <queue>#include <cstring>#include <iostream>#include <cstdlib>#include <algorithm>#include <vector>#include <map>#include <string>#include <set>#include <ctime>#include <cmath>#include <cctype>using namespace std;#define maxn 100001#define LL long longint cas=1,T;int n;vector<int>G[maxn];int in[maxn];int e[maxn],e1[maxn];bool topo(int m){memset(in,0,sizeof(in));for (int i = 0;i<=n;i++)G[i].clear();for (int i = 1;i<=m;i++){G[e[i]].push_back(e1[i]);in[e1[i]]++;}queue<int>q;int sum = 0;for (int i = 1;i<=n;i++)if (in[i]==0)q.push(i);while (!q.empty()){int u = q.front();q.pop();if (q.size())return false;sum++;for (int i = 0;i<G[u].size();i++){int v = G[u][i];if (--in[v]==0)q.push(v);}}return true;//return sum==n;}int main(){    int k;while (scanf("%d%d",&n,&k)!=EOF){        for (int i = 1;i<=k;i++)scanf("%d%d",&e[i],&e1[i]);int l=1,r=k;int ans = -1;while (l<=r){            int m = (l+r)/2;if (topo(m))r=m-1,ans=m;elsel=m+1;}printf("%d\n",ans);}//freopen("in","r",stdin);//scanf("%d",&T);//printf("time=%.3lf",(double)clock()/CLOCKS_PER_SEC);return 0;}

Description

While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots operate under deterministic algorithms. In particular, robot i will beat robot j if and only if robot i has a higher skill level than robot j. And if robot i beats robot j and robot j beats robot k, then robot i will beat robot k. Since rapping is such a subtle art, two robots can never have the same skill level.

Given the results of the rap battles in the order in which they were played, determine the minimum number of first rap battles that needed to take place before Bessie could order all of the robots by skill level.

Input

The first line of the input consists of two integers, the number of robots n (2 ≤ n ≤ 100 000) and the number of rap battles m ().

The next m lines describe the results of the rap battles in the order they took place. Each consists of two integers ui and vi (1 ≤ ui, vi ≤ nui ≠ vi), indicating that robot ui beat robot vi in the i-th rap battle. No two rap battles involve the same pair of robots.

It is guaranteed that at least one ordering of the robots satisfies all m relations.

Output

Print the minimum k such that the ordering of the robots by skill level is uniquely defined by the first k rap battles. If there exists more than one ordering that satisfies all m relations, output -1.

Sample Input

Input
4 52 11 32 34 24 3
Output
4
Input
3 21 23 2
Output
-1


0 0
原创粉丝点击