【hdu 5638】Toposort 中文题意&题解&代码(C++)

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值