题目链接:
/*
Name:hdoj-2647-Reward
Copyright:
Author:
Date: 2018/4/11 15:59:18
Description:
*/
#include <iostream>
#include <queue>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 1e+;
int du[MAXN], n , m, L[MAXN];
vector<int> g[MAXN];
bool topsort() {
memset(du, , sizeof(du));
for (int i=; i<n; i++) {
for (int j=; j<g[i].size(); j++) {
du[g[i][j]]++;
}
}
int tot = ;
queue<int> Q;
for (int i=; i<n; i++) {
if (!du[i]) {
Q.push(i);
L[i] = ;
}
}
while (!Q.empty()) {
int x = Q.front();
Q.pop();
tot++;
for (int j=; j<g[x].size(); j++) {
int t = g[x][j];
du[t]--;
if (!du[t]) {
Q.push(t);
L[g[x][j]] = L[x] + ;
}
}
}
if (tot == n) return ;
return ;
}
int main()
{
// freopen("in.txt", "r", stdin);
while (cin>>n>>m && (m || n)) {
memset(L, , sizeof(L));
memset(g, , sizeof(g));
for (int i=; i<m; i++) {
int a, b;
cin>>a>>b;
a--;
b--;
g[b].push_back(a);
}
if (topsort() == ) {
int sum = ;
for (int i=; i<n; i++) {
sum += L[i];
}
cout<<sum+n*<<endl;
}
else cout<<"-1"<<endl;
}
return ;
}