http://acm.hdu.edu.cn/showproblem.php?pid=2647
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#define MM 10005
using namespace std;
int inde[MM];
int add[MM]; //每人要加的。
struct Node
{
int data;
Node *next;
Node():data(0),next(0){}
}*e[MM];
void addEdage(int u,int v)
{
Node *t =new Node;
t->data=v;
t->next=e[u];
e[u]=t;
}
void init(int n)
{
memset(e,0,sizeof(e));
memset(inde,0,sizeof(inde));
int i;
for(i=0;i<=n;i++)
add[i]=888;
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
int i,a,b;
init(n);
for(i=0;i<m;i++)
{
scanf("%d%d",&a,&b);
addEdage(b,a); //注意是反向的
inde[a]++;
}
queue<int> q;
for(i=1;i<=n;i++)
{
if(inde[i]==0)
{
q.push(i);
}
}
int sum=0;
int count=0;
while(!q.empty())
{
int t=q.front();
q.pop();
count++;
sum=sum+add[t];
Node *hh;
for(hh=e[t];hh;hh=hh->next)
{
if(--inde[hh->data]==0)
{
q.push(hh->data);
add[hh->data]=add[t]+1; //注意点
}
}
}
if(count!=n)
printf("-1\n");
else
printf("%d\n",sum);
}
return 0;
}
HDU 2647 题解
本文提供了一种解决HDU 2647问题的算法实现方案,采用C++语言通过拓扑排序的方法求解,具体包括节点结构定义、边的添加、初始化、主循环等步骤。
1492

被折叠的 条评论
为什么被折叠?



