hdu 2647
来源:互联网 发布:无损播放软件排名 编辑:程序博客网 时间:2024/05/14 14:46
一道拓扑排序题 改了好久 桑心
#include<iostream>
#include<cstdio>#include<cstring>
#include<queue>
#define MAXN 10050
using namespace std;
int n,m,ans;
int head[MAXN];//头指针
struct node
{
int to;//边的起点
int next;//边的终点
}edge[MAXN*2];//边
int tol;
int add(int a,int b)//加边的过程
{
edge[tol].to=b;
edge[tol].next=head[a];
head[a]=tol++;
}
int in[MAXN];//入路
int f[MAXN];//价格
int tuopu()//拓扑排序
{
queue<int>q;//一个队列q
for(int i=1;i<=n;i++)
{
if(in[i]==0)//如果入路为0
q.push(i);//将其推入队列
f[i]=888;//有最小值888
}
int cnt=0;//点
while(!q.empty())
{
int x=q.front();
cnt++;
q.pop();//第一个值出队列
for(int i=head[x];i!=-1;i=edge[i].next)
{
int to=edge[i].to;//to 上一条边的起点
in[to]--;//上一条边入路-1
if (in[to]==0)
{
q.push(to);
f[to]=max(f[to],f[x]+1);
} //上一条的价格=上条边的始点的价钱
//与本条边的价钱+1取大值
else
{
f[to]=f[x]+1;
}
}
}
for(int i=1;i<=n;i++)
{
ans+=f[i];
}
if(cnt!=n)//判断是否成环
{//如果没有环 一定有n个点
return 0;
}
else
return 1;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
int a,b;
memset(head,-1,sizeof(head));//清零
memset(in,0,sizeof(in));
memset(f,0,sizeof(f));
tol=0;
ans=0;
for(int i=0;i<m;i++)
{
scanf("%d%d",&a,&b);
add(b,a);
in[a]++;
}
if(tuopu())
{
printf("%d\n",ans);
}
else
printf("-1\n");
}
return 0;
}
阅读全文
1 0
- hdu 2647
- HDU 2647
- hdu 2647
- hdu 2647
- hdu 2647 Reward
- hdu 2647 (拓扑)
- hdu 2647 Reward
- hdu 2647 Reward
- HDU-2647拓扑排序
- HDU 2647 Reward
- hdu 2647 Reward
- hdu 2647 Reward
- hdu 2647 拓扑排序
- hdu 2647 拓扑排序
- hdu-2647 Reward
- 拓扑排序 HDU 2647
- hdu 2647 Reward
- HDU 2647 Reward
- CPU性能瓶颈
- 命令行参数
- HDU 1010 Tempter of the Bone
- 开启宽带默认限制 window提升上网速度 window百分之百上网
- Intelligence System (强连通 + 缩点)
- hdu 2647
- mysql去空缺排序
- IP设置和网关设置
- 7.29 队列
- UVa 10325 The Lottery 【容斥】【入门】
- Quicksum
- SpringBoot13-springboot核心-基本配置
- Leetcode_80_Remove Duplicates from Sorted Array II
- 暴力求解法--生成子集