• Luogu_P2886 [USACO07NOV]牛继电器Cow Relays【题解】图论 矩阵快速幂


    Luogu_P2886 [USACO07NOV]牛继电器Cow Relays

    图论 矩阵快速幂


    题目链接
    POJ3613
    题意就是求经过k条边的从st到ed的最短路
    我们假设(a[i][j])为经过一条边的最短路
    (a2[i][j])为经过两条边的。
    那么(a2[i][j]=min(a[i][k]+a[k][j]))
    那么其实这就是一个类似矩阵快速幂的东西
    只不过是把(+)(*)变成(min)(+)
    那么就把原数离散化之后矩阵运算


    代码如下:

    #include<cstdio>
    #include<cstring>
    #include<map>
    using namespace std;
    const int maxn=300,inf=0x3f3f3f3f;
    int n,m,st,ed,tot;
    map<int,int> ls;
    struct node{
    	int c[maxn][maxn];
    }ans,base;
    inline node mul(node x,node y){
    	node res;memset(res.c,inf,sizeof(res.c));
    	for(int i=1;i<=tot;i++)
    		for(int k=1;k<=tot;k++){
    			if(x.c[i][k]>=inf) continue;
    			for(int j=1;j<=tot;j++)
    				res.c[i][j]=min(res.c[i][j],x.c[i][k]+y.c[k][j]);
    		}
    	return res;
    }
    inline void qp(int x){
    	while(x){
    		if(x&1) ans=mul(ans,base);
    		base=mul(base,base);
    		x>>=1;
    	}
    }
    int main()
    {
    	scanf("%d%d%d%d",&n,&m,&st,&ed);tot=0;
    	memset(base.c,inf,sizeof(base.c));memset(ans.c,inf,sizeof(ans.c));
    	for(int i=1;i<=m;i++){
    		int x,y,z;scanf("%d%d%d",&z,&x,&y);
    		x=ls[x] ? ls[x] : (ls[x]=++tot);
    		y=ls[y] ? ls[y] : (ls[y]=++tot);
    		ans.c[x][y]=ans.c[y][x]=z;base.c[x][y]=base.c[y][x]=z;
    	}
    	qp(n-1);
    	printf("%d
    ",ans.c[ls[st]][ls[ed]]);
    	return 0;
    }
    
  • 相关阅读:
    AFNetwork 作用和用法详解
    ios 常见错误记录
    UIView的setNeedsLayout, layoutIfNeeded 和 layoutSubviews 方法之间的关系解释
    AutoLayout
    矩阵的法式
    极小多项式
    对角化
    线性映射
    线性方程组的解
    特征值和特征向量
  • 原文地址:https://www.cnblogs.com/ChrisKKK/p/11604114.html
Copyright © 2020-2023  润新知