标签:bc #35 hdu 5195 topsort+优先队列
5 5 2 1 2 4 5 2 4 3 4 2 3 3 2 0 1 2 1 3
5 3 1 2 4 1 3 2HintCase 1. Erase the edge (2->3),(4->5). And the lexicographically largest topological ordering is (5,3,1,2,4).
题意:n个点m条有向边组成的有向无环图,可以最多删除k条边让他的拓扑序最大。输出最大的拓扑序。
思路:在以前的topsort中是入读为零的点入队列,这里有k次机会可以删除边,那么我就把所有入度<=k的点全入队列,用优先队列维护最大的点序列号,去掉点最大序列号的所有入边,将它加入到拓扑序中,这样贪心是最优的。
13278437 | 2015-03-29 09:39:39 | Accepted | 5195 | 374MS | 8344K | 2822 B | C++ | wust_lyf |
13278469 | 2015-03-29 09:42:51 | Accepted | 5195 | 1996MS | 10928K | 2822 B | G++ | wust_lyf |
G++和C++差别如此大
代码:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <string> #include <map> #include <stack> #include <vector> #include <set> #include <queue> #pragma comment (linker,"/STACK:102400000,102400000") #define maxn 200005 #define MAXN 2005 #define mod 1000000009 #define INF 0x3f3f3f3f #define pi acos(-1.0) #define eps 1e-6 #define lson rt<<1,l,mid #define rson rt<<1|1,mid+1,r #define FRE(i,a,b) for(i = a; i <= b; i++) #define FREE(i,a,b) for(i = a; i >= b; i--) #define FRL(i,a,b) for(i = a; i < b; i++) #define FRLL(i,a,b) for(i = a; i > b; i--) #define mem(t, v) memset ((t) , v, sizeof(t)) #define sf(n) scanf("%d", &n) #define sff(a,b) scanf("%d %d", &a, &b) #define sfff(a,b,c) scanf("%d %d %d", &a, &b, &c) #define pf printf #define DBG pf("Hi\n") typedef long long ll; using namespace std; struct Node { int x; int id; friend bool operator<(const Node a,const Node b) { return a.id<b.id; } }; int n,m,k; vector <int> edge[maxn]; priority_queue<Node> Q; int inDegree[maxn]; int ans[maxn]; int vis[maxn]; int main() { int i; while(scanf("%d%d%d",&n,&m,&k)!=EOF) { for (i=0;i<=n+2;i++) { edge[i].clear(); inDegree[i]=0; vis[i]=0; //不在队列中 ans[i]=0; } for (i=0;i<m;i++) { int a,b; scanf("%d%d",&a,&b); inDegree[b]++; edge[a].push_back(b); } while(!Q.empty()) Q.pop(); Node node; for (i=1;i<=n;i++) if (inDegree[i]<=k) { node.id=i; node.x=inDegree[i]; Q.push(node); vis[i]=1;//在队列中 } int t=0; while (!Q.empty()) { Node now=Q.top(); Q.pop(); if (inDegree[now.id]<=k) k-=inDegree[now.id]; else { vis[now.id]=0; continue; } vis[now.id]=2;//已经输出 ans[t++]=now.id; for (i=0;i<edge[now.id].size();i++) { int v=edge[now.id][i]; inDegree[v]--; node.id=v; node.x=inDegree[v]; if (inDegree[v]<=k && vis[v]==0) { Q.push(node); vis[v]=1; } } } pf("%d",ans[0]); for (int i=1;i<t;i++) pf(" %d",ans[i]); pf("\n"); } return 0; } /* 6 6 2 5 6 1 2 4 5 2 4 3 4 2 3 3 2 0 1 2 1 3 */
DZY Loves Topological Sorting (BC #35 hdu 5195 topsort+优先队列)
标签:bc #35 hdu 5195 topsort+优先队列
原文地址:http://blog.csdn.net/u014422052/article/details/44724587