poj 3613


Problem : 问从 S T 经过边得个数恰为k的最短路是多少。
Solution : 做 k Floyd 即可,使用分治[快速幂]思想优化


#include<map>
#include<queue>
#include<stack>
#include<utility>
#include<string>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<cmath>
#include<iostream>
#include<algorithm>
#define Mp(x,y) std::make_pair(x,y)

const int MAXT = 105,INF = (1<<30)-1,MAXN = 205;

int n ,k , T , s , e;
struct Matrix
{
    int n, mat[MAXN][MAXN];
}A;

struct Edge{int u,v,w;Edge(int u = 0,int v = 0,int w = 0):u(u),v(v),w(w){}}star[MAXT<<1] = {0};

Matrix Floyd(Matrix A,Matrix B)
{
    Matrix C; 

    C.n = A.n;
    for(int i = 1; i <= C.n; i++)
      for(int j = 1;j <= C.n; j++)
         C.mat[i][j] = INF;

    for(int i = 1; i <= A.n; i++)
      for(int j = 1; j <= B.n; j++)
        for(int k = 1; k <= C.n; k++)
            C.mat[i][j] = std::min(C.mat[i][j],A.mat[i][k] + B.mat[k][j]);

    return C;       
}

int bowl[MAXT<<1] = {0},blen = 0;

Matrix PowerMat(Matrix X,int p)
{
    Matrix ret = X;

    while(p)
    {
        if(p&1)ret = Floyd(ret,X);
        X = Floyd(X,X), p >>= 1;
    }
    return ret;
}

int main()
{
#ifndef ONLINE_JUDGE
    freopen("poj3613.in","r",stdin);
    freopen("poj3613.out","w",stdout);
#endif

    std::cin >> k >> T >> s >> e;
    for(int i = 1,a,b,l; i <= T; i++)
    {
        std::cin >> l >> a >> b;
        star[(i<<1)-1] = Edge(a,b,l);
        star[i<<1] = Edge(b,a,l);
        bowl[++blen] = a, bowl[++blen] = b;
    }
    std::sort(bowl+1,bowl+blen+1);
    blen = std::unique(bowl+1,bowl+blen+1) - (bowl+1);

    for(int i = 1; i <= (T<<1); i++)
    {
        star[i].u = std::lower_bound(bowl+1,bowl+blen+1,star[i].u) - bowl;
        star[i].v = std::lower_bound(bowl+1,bowl+blen+1,star[i].v) - bowl;
    }
    s = std::lower_bound(bowl+1,bowl+blen+1,s) - bowl;
    e = std::lower_bound(bowl+1,bowl+blen+1,e) - bowl;

    A.n = blen;
    for(int i = 1; i <= A.n; i++)
      for(int j = 1;j <= A.n; j++)
        A.mat[i][j] = INF;

    for(int i = 1 ;i <= (T<<1); i++)
       if(star[i].w < A.mat[star[i].u][star[i].v])
        A.mat[star[i].u][star[i].v] = star[i].w;


    std::cout << PowerMat(A,k-1).mat[s][e] << std::endl;

    fprintf(stderr,"%f",clock()*1.0/CLOCKS_PER_SEC);
#ifndef ONLINE_JUDGE
    fclose(stdin);
    fclose(stdout);
#endif
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值