【hdu 5638】Toposort 中文题意&题解&代码(C++)
2016-03-07 21:13
561 查看
Toposort
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Problem Description
There is a directed acyclic graph with n vertices and m edges. You are allowed to delete exact k edges in such way that the lexicographically minimal topological sort of the graph is minimum possible.
Input
There are multiple test cases. The first line of input contains an integer T indicating the number of test cases. For each test case:
The first line contains three integers n, m and k (1≤n≤100000,0≤k≤m≤200000) – the number of vertices, the number of edges and the number of edges to delete.
For the next m lines, each line contains two integers ui and vi, which means there is a directed edge from ui to vi (1≤ui,vi≤n).
You can assume the graph is always a dag. The sum of values of n in all test cases doesn’t exceed 106. The sum of values of m in all test cases doesn’t exceed 2×106.
Output
For each test case, output an integer S=(∑i=1ni⋅pi) mod (109+7), where p1,p2,…,pn is the lexicographically minimal topological sort of the graph.
Sample Input
3
4 2 0
1 2
1 3
4 5 1
2 1
3 1
4 1
2 3
2 4
4 4 2
1 2
2 3
3 4
1 4
Sample Output
30
27
30
中文题意:
给出n个点,m条边,再给你可以删掉k条边的权利,求出字典序最小的拓扑序,再按题上要求的求和方式输出答案。
题解:
用优先队列来做,一开始将所有节点全部push进队列里,每次取优先队列中编号最小的点,判断一下入度是否小于当前的k,如果小于则将找到的这个节点删除,k-=这个节点的入度。
代码
#include<iostream> #include<algorithm> #include<stdio.h> #include<vector> #include<queue> using namespace std; vector<int>lin[100005]; priority_queue<int>q; int tot=0,x,y,k,n,m,T,in[100005],out[100005],vis[100005]; long long ans=0; int main() { long long mmod=1e9+7; scanf("%d",&T); while(T--) { ans=0;tot=0; scanf("%d%d%d",&n,&m,&k); while(!q.empty()) q.pop(); for (int i=1;i<=n;i++) { q.push(0-i); lin[i].clear(); in[i]=0; vis[i]=0; } for (int i=1;i<=m;i++) { scanf("%d%d",&x,&y); lin[x].push_back(y); in[y]++; } while(!q.empty()) { int now=0-q.top();q.pop(); if (vis[now]) continue; if (in[now]<=k) { tot++; k-=in[now]; in[now]=0; ans=(ans+(long long)tot*(long long)now)%mmod; vis[now]=1; for (int i=0;i<lin[now].size();i++) { int nex=lin[now][i]; if (in[nex]) { in[nex]--; q.push(0-nex); } } } } // printf("%I64d\n",ans); cout<<ans<<endl; } }
相关文章推荐
- 二叉树的C++指针实现
- C++标准库简介、与STL的关系。
- STL之顺序容器和关联容器总结
- 【hdu 5637】Transform 中文题意&题解&代码(C++)
- C++中多线程的加锁机制
- C++ STL--stack/queue 的使用方法
- 关于C++的问题
- 1102. Invert a Binary Tree (25)
- 【hdu 5636】Shortest Path 中文题意&题解&代码(C++)
- C++模板归并排序
- C/C++中的位运算(下)
- 2.C语言数据类型
- 【hdu 5635】LCP Array 中文题意&题解&代码(C++)
- C++ 知识点备忘
- C++模板插入排序
- Effictive C++笔记
- C/C++中的位运算(上)
- 深入学习C++.2016_3_7
- Cpp--拷贝构造函数
- 九度OJ 1207:质因数的个数