标签:
Time Limit: 6000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 437 Accepted Submission(s): 157
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <algorithm>
#include <set>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define MM(a,b) memset(a,b,sizeof(a));
const double eps = 1e-10;
const int inf =0x7f7f7f7f;
const double pi=acos(-1);
const int maxn=100+100000;
int deg[maxn];
vector<int> G[maxn];
struct node{
int id;
bool operator<(const node &b) const
{
return this->id<b.id;
}
}ne[maxn];
int main()
{
int cas,n,m;
scanf("%d",&cas);
while(cas--)
{
scanf("%d %d",&n,&m);
ll ans=0;
for(int i=1;i<=n;i++)
{
G[i].clear();
ne[i].id=i;
}
memset(deg,0,sizeof(deg));
priority_queue<node> q;
for(int i=1;i<=m;i++)
{
int u,v;
scanf("%d %d",&u,&v);
G[u].push_back(v);
deg[v]++;
}
for(int i=1;i<=n;i++) if(!deg[i]) q.push(ne[i]);
int minn=n+1;
while(q.size())
{
node k=q.top();q.pop();
int u=k.id;
minn=min(minn,u);
ans+=minn;
for(int j=0;j<G[u].size();j++)
{
int v=G[u][j];
deg[v]--;
if(!deg[v]) q.push(ne[v]);
}
}
printf("%lld\n",ans);
}
return 0;
}
分析:很好的一道题,,题目中A B意味着要想选B得必须先选A,那么我们可以由A向B连接一条边
,最后构建了图后,考虑选第一个点时,入度为不为0的点是肯定不能选的,那么我们只能在入度入度为0
的点中选,根据贪心的原则,我们选编号最大的作为第一个点(优先队列维护),然后再删除与之相连结的边,再将新出现的入度位0的点压入优先队列。
标签:
原文地址:http://www.cnblogs.com/smilesundream/p/5515658.html