题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5695
题解:拓扑序列贪心下每次取最大点,用优先队列就好
//#include <bits/stdc++.h>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
int Scan()
{
int res=0,ch,flag=0;
if((ch=getchar())=='-')flag=1;
else if(ch>='0'&&ch<='9')res=ch-'0';
while((ch=getchar())>='0'&&ch<='9')res=res*10+ch-'0';
return flag?-res:res;
}
void Out(int a)
{
if(a>9)Out(a/10);
putchar(a%10+'0');
}
#define INF 0x3f3f3f3f
#define bug cout<<"bug"<<endl
const int MAXN = 1e5+7;
priority_queue<int>qi;
vector<int> nod[MAXN];
int link[MAXN];
int head[MAXN];
int num[MAXN];
int main()
{
int T;
int m,n;
cin>>T;
int cas=1;
int a,b;
while(T--)
{
scanf("%d%d",&n,&m);
memset(head,0,sizeof(head));
for(int i=0; i<n; ++i)nod[i].clear();
for(int i=0; i<m; ++i)
{
scanf("%d%d",&a,&b);
nod[a].push_back(b);
head[b]++;
}
for(int i=1; i<=n; ++i)
if(head[i]==0)
qi.push(i);
int temp=0;
while(!qi.empty())
{
int poi=qi.top();
qi.pop();
num[temp++]=poi;
int len=nod[poi].size();
for(int i=0; i<len; ++i)
{
head[ nod[poi][i] ]--;
if(head[ nod[poi][i] ]==0)
qi.push(nod[poi][i]);
}
}
long long ans=0;
int minn=INF;
for(int i=0; i<n ; ++i)
{
if(num[i]<minn)
minn=num[i];
ans+=minn;
}
printf("%I64d\n",ans);
}
return 0;
}