2019CCPC网络赛:1004 path

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6705

题目截图:

解题方法:很容易就能想到使用优先队列来求第k小的路径,那么还有一个问题就是是不是当前节点的所有的儿子都要加到优先队列里面?当然不是这样的,因为这样内存会超限而且也会TLE。我们可以想到当前状态要走接下来小的路径有几种情况?有一种情况就是走儿子的边权值最小的那一条。还有一种情况就是往回走一步然后再往下走下一个rank的路径都比当前状态大一点点。

代码如下:

#include<bits/stdc++.h>
#define FRD freopen("in.txt", "r", stdin)
#define __ctz(x) __builtin_ctz(x)               //返回二进制下末尾有几个零
#define __ffs(x) __builtin_ffs(x)               //返回二进制下最后一个1的位置,从1开始
#define ms(x,y) memset(x,y,sizeof(x))
#define pb push_back
#define mk make_pair
#define all(x) x.begin(),x.end()
#define lson (id<<1)
#define rson (id<<1|1)
#define fi first
#define se second
using namespace std;
typedef long long int LL;
typedef pair<LL,LL> pll;
const LL INF = 1e18;
const int N = 1e5+7;
int n,m,q;
struct Edg{
    int v, w;
    bool operator < (const Edg &rhs) const{
        return w < rhs.w;
    }
};
vector<Edg> G[N];
struct Node{
    int u,v,rank;
    LL val;
    bool operator < (const Node &rhs) const{
        return val > rhs.val;
    }
};
LL now_max = 0;
priority_queue<Node> que;
int qs[N];
LL res[N];
void solve(int k) {
    int cnt = 0;
    while (!que.empty()) {
        Node now = que.top(); que.pop();
        res[++cnt] = now.val;
        if (cnt >= k) return ;
	if (G[now.u].size() > now.rank+1) {
		que.push((Node){now.u,G[now.u][now.rank+1].v,now.rank+1,now.val+G[now.u][now.rank+1].w-G[now.u][now.rank].w});
	}
	if (G[now.v].size() > 0) {
		que.push((Node){now.v,G[now.v][0].v,0,G[now.v][0].w+now.val});
	}
    }
}
int main() {
    #ifndef ONLINE_JUDGE
        int startTime = clock();
        FRD;
    #endif
    int T; scanf("%d", &T);
    while (T--) {
        scanf("%d%d%d", &n,&m,&q);
        while (!que.empty()) que.pop(); 
        for (int i = 1; i <= n; i++) {
            G[i].clear();
        }
        now_max = 0;
        for (int i = 1; i <= m; i++) {
            int u,v,w; 
            scanf("%d%d%d", &u,&v,&w);
            G[u].pb((Edg){v,w});
        }
        for (int i = 1; i <= n; i++) {
            sort(all(G[i]));
            if (G[i].size() > 0) {
            	que.push((Node){i,G[i][0].v,0,G[i][0].w});
			}
        }
        int k = 0;
        for (int i = 1; i <= q; i++) {
            scanf("%d", &qs[i]);
            k = max(k,qs[i]);
        }
        solve(k);
        for (int i = 1; i <= q; i++) {
            cout << res[qs[i]] << endl;
        }
    }
    #ifndef ONLINE_JUDGE
        printf("Time = %dms\n", clock() - startTime);
    #endif
    return 0;
}

代码总结:优先队列是最大值优先,写的时候又给忘记了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值