您的位置:首页 > 运维架构

hdu 5195 DZY Loves Topological Sorting(线段树)

2016-07-25 11:07 465 查看


DZY Loves Topological Sorting

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)

Total Submission(s): 1065    Accepted Submission(s): 328


Problem Description

A topological sort or topological ordering of a directed graph is a linear ordering of its vertices such that for every directed edge (u→v) from
vertex u to
vertex v, u comes
before v in
the ordering.

Now, DZY has a directed acyclic graph(DAG). You should find the lexicographically largest topological ordering after erasing at most k edges
from the graph.

 

Input

The input consists several test cases. (TestCase≤5)

The first line, three integers n,m,k(1≤n,m≤105,0≤k≤m).

Each of the next m lines
has two integers: u,v(u≠v,1≤u,v≤n),
representing a direct edge(u→v).

 

Output

For each test case, output the lexicographically largest topological ordering.

 

Sample Input

5 5 2
1 2
4 5
2 4
3 4
2 3
3 2 0
1 2
1 3

 

Sample Output

5 3 1 2 4
1 3 2

HintCase 1.
Erase the edge (2->3),(4->5).
And the lexicographically largest topological ordering is (5,3,1,2,4).

题意:求删除k条边后字典序最大的拓扑排序

思路:一开始想在拓扑排序里面改,可是怎么也贪心不出来。

后面才知道能用线段树去维护,每次取入度<=k的边,并且编号尽量大(也就是尽量往右取),然后每次取完更新即可。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
#define N 100005
#define INF 999999999
struct Edge
{
int v,next;
}edge
;
int tree[N<<2];
int num
,cnt,head
;
int ans,k;
void init()
{
cnt=0;
memset(num,0,sizeof(num));
memset(head,-1,sizeof(head));
}
void addedge(int u,int v)
{
edge[cnt].v=v;
edge[cnt].next=head[u];
head[u]=cnt++;
}
void pushup(int root)
{
tree[root]=min(tree[root<<1],tree[root<<1|1]);
}
void build(int root,int l,int r)
{
if(l==r)
{
tree[root]=num[l];
return;
}
int mid=(l+r)>>1;
build(root<<1,l,mid);
build(root<<1|1,mid+1,r);
pushup(root);
}
void query(int root,int l,int r)
{
if(l==r)
{
k-=tree[root];
ans=l;
tree[root]=INF;
return;
}
int mid=(l+r)>>1;
if(tree[root<<1|1]<=k) query(root<<1|1,mid+1,r);
else query(root<<1,l,mid);
pushup(root);
}
void update(int pos,int root,int l,int r)
{
if(l==r)
{
tree[root]--;
return;
}
int mid=(l+r)>>1;
if(mid>=pos) update(pos,root<<1,l,mid);
else update(pos,root<<1|1,mid+1,r);
pushup(root);
}
int main()
{
int n,m;
int u,v;
while(~scanf("%d %d %d",&n,&m,&k))
{
init();
for(int i=1; i<=m; i++)
{
scanf("%d %d",&u,&v);
addedge(u,v);
num[v]++;
}
build(1,1,n);
for(int i=1;i<=n;i++)
{
query(1,1,n);
printf("%d",ans);
if(i<n) printf(" ");
else printf("\n");
update(ans,1,1,n);
for(int i=head[ans];i!=-1;i=edge[i].next)
{
int v=edge[i].v;
num[v]--;
update(v,1,1,n);
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: