Click here for the topic link! ! ! !
The main idea of the topic:
you pay n people. They have their own requirements. The salary of a must be greater than that of b. Each person's salary is at least 888 (lucky). You are required to find the minimum salary. If they cannot be satisfied If required, -1 is output. Enter ab to indicate that a's salary must be greater than b. (No re-edge)
Idea:
As long as you see this kind of requirements, most of the questions that must be before something are related to the final topological sequence. The question requires a>b, so after the salary is paid to b, add 1 to the salary of b and then send it to a (another sequential relationship), so it is ok to find the final topological sequence .
However, there is one point that may be wrong if you are too brainy, that is, the input order is ab. The meaning of the representative is a>b, so a is behind b, so the direction of this side in the DAG we build is b to a. Then nothing can go wrong.
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N=1e4+10,M=2e4+10;
struct edge
{
int to,next;
}e[M];
struct node
{
int id,val;
node(int a=0,int b=0):id(a),val(b){
}
};
int head[N],cnt=0,n,m,du[N],ans,k;
void addedge(int u,int v)
{
e[++cnt].to=v;
e[cnt].next=head[u];
head[u]=cnt;
}
void topsort()
{
queue<node>q;
for(int i=1;i<=n;i++) if(!du[i]) q.push(node(i,888));
k=0;
while(!q.empty())
{
node now=q.front();q.pop();
k++;
ans+=now.val;
for(int i=head[now.id];i;i=e[i].next)
{
int to=e[i].to;
du[to]--;
if(!du[to]) q.push(node(to,now.val+1));
}
}
}
int main()
{
while(scanf("%d%d",&n,&m)==2)
{
cnt=0;
memset(head,0,sizeof(head));
memset(du,0,sizeof(du));
for(int i=1;i<=m;i++)
{
int x,y;
scanf("%d%d",&x,&y);
addedge(y,x);
du[x]++;
}
ans=0;
topsort();
if(k==n) printf("%d\n",ans);
else printf("-1\n");
}
return 0;
}