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 jand 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 ≤ n, ui ≠ 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 mrelations.
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.
Examples
Input
4 5 2 1 1 3 2 3 4 2 4 3
Output
4
Input
3 2 1 2 3 2
Output
-1
Note
In the first sample, the robots from strongest to weakest must be (4, 2, 1, 3), which Bessie can deduce after knowing the results of the first four rap battles.
In the second sample, both (1, 3, 2) and (3, 1, 2) are possible orderings of the robots from strongest to weakest after both rap battles.
题意:
给定n个机器人的m个能力大小关系,问你至少要前几个大小关系就可以得到所有机器人的能力顺序。
思路:
这题第一感觉拓扑排序,当时没做出来,后来看博客是二分答案,然后拓扑排序看看是否成一条直线即可
#include<stdio.h>
#include<queue>
#include<string.h>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int n;
vector<int>g[100010];
int s[100010];
int a[100010],b[100010];
int tp(int m)
{
memset(s,0,sizeof(s));
for (int i=0; i<=n; i++)
g[i].clear();
for (int i=1; i<=m; i++)
{
g[a[i]].push_back(b[i]);
s[b[i]]++;
}
queue<int>Q;
int sum=0;
for (int i=1; i<=n; i++)
if (s[i]==0)
Q.push(i);
while (!Q.empty())
{
int u=Q.front();
Q.pop();
if (Q.size())
return 0;
sum++;
for (int i=0; i<g[u].size(); i++)
{
int v=g[u][i];
if (--s[v]==0)
Q.push(v);
}
}
return 1;
}
int main()
{
int k;
while (~scanf("%d%d",&n,&k))
{
for (int i=1; i<=k; i++)
scanf("%d%d",&a[i],&b[i]);
int l=1,r=k;
int ans = -1;
while (l<=r)
{
int m=(l+r)/2;
if (tp(m))
{
r=m-1;
ans=m;
}
else
l=m+1;
}
printf("%d\n",ans);
}
return 0;
}