题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=5695
题意:中文题,不解释
题解:逆向拓扑字典序就行
#include<cstdio>
#include<string>
#include<set>
#include<vector>
#include<queue>
#include<functional>
using namespace std;
#define MAX 100010
int InDeg[MAX];
int n, m, Count;
int Ans[MAX];
vector<int> v[MAX];
void TopoSort()
{
priority_queue<int> PQ;
for(int i=n; i>=1; i--) //找出入度为0的点并放入优先队列
if(InDeg[i]==0) PQ.push(i);
while(!PQ.empty()) //BFS
{
int Tmp = PQ.top();
PQ.pop();
Ans[Count++] = Tmp;
for(int i=0; i<v[Tmp].size(); i++)
{
InDeg[v[Tmp][i]]--;
if(InDeg[v[Tmp][i]]==0) PQ.push(v[Tmp][i]);
}
}
}
int main()
{
int x, y,t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for(int i=0;i<=n;i++)v[i].clear(),InDeg[i]=0;
Count = 0;
for(int i=0; i<m; i++)
{
scanf("%d%d",&x,&y);
InDeg[y]++;
v[x].push_back(y);
}
TopoSort();
int min=1000000000;
long long an=0;
for(int i=0; i<Count; i++){
min=min>Ans[i]?Ans[i]:min;
an+=min;
}
printf("%I64d\n",an);
}
}