#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#define inf 0x3f3f3f3f
using namespace std;
const int N=1e4+5;
int n,m,in[N],x,y;
vector<int> a[N];
int topo()
{
queue<int> q;
for(int i=1;i<=n;i++)
if(in[i]==0)
q.push(i);
int num=0,s=0,x=888;
while(!q.empty())
{
int len=q.size();
while(len--)
{
int t=q.front();
q.pop();
num++;
s+=x;
for(int i=0;i<a[t].size();i++)
{
if(--in[a[t][i]]==0)
q.push(a[t][i]);
}
}
x++;
}
if(num<n)
return -1;
else
return s;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
while(cin >> n >> m)
{
memset(in,0,sizeof(in));
for(int i=1;i<=n;i++)
a[i].clear();
while(m--)
{
cin >> x >> y;
in[x]++;
a[y].push_back(x);
}
cout << topo() << endl;
}
return 0;
}
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#define inf 0x3f3f3f3f
using namespace std;
const int N=1e4+5;
int n,m,in[N],x,y;
vector<int> a[N];
struct node
{
int id,depth;
};
int topo()
{
queue<node> q;
for(int i=1;i<=n;i++)
if(in[i]==0)
q.push({i,0});
int num=0,s=0,x=888;
while(!q.empty())
{
node t=q.front();
q.pop();
num++;
s+=x+t.depth;
for(int i=0;i<a[t.id].size();i++)
{
if(--in[a[t.id][i]]==0)
q.push({a[t.id][i],t.depth+1});
}
}
if(num<n)
return -1;
else
return s;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
while(cin >> n >> m)
{
memset(in,0,sizeof(in));
for(int i=1;i<=n;i++)
a[i].clear();
while(m--)
{
cin >> x >> y;
in[x]++;
a[y].push_back(x);
}
cout << topo() << endl;
}
return 0;
}