Cow Relays(POJ 3613)

这道题困扰我一学期了,大意是求多源最短路径并要求每条路径的长度恰好为N,感觉上可以直接用矩阵乘法来做,只是此时矩阵乘法的乘变为广义乘,同时注意初始化(一开始直接在之前数据基础上求,导致一直WA。。)。另外由于图的点数有1000,但是给出的边只有100,所以实际用到的点数只有200以下,具体实现的过程中采用了set记录并简化的方法(当然后来才发现用map的实现更加方便)。另外应该用到矩阵快速幂的方法,学习了(相比自己的笨笨的开了20个数组,后来才发现一大堆都是可以现场计算并且进行动态更新的)。

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <iostream>
#include <string.h>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
#define MAXN 202
#define INF 0x3f3f3f3f
typedef long long ll;
ll relayDistance[4][MAXN][MAXN];
set<int > vertices;
int verticesMatch[1003];
typedef struct edge {
	int u;
	int v;
	int length;
	struct edge(){}
	struct edge(int uu, int vv, int lengta) { u = uu; v = vv; length = lengta; }
}Edge;
int N, T, S, E;
int graphSize;
Edge edges[101];
void setMatrix(int No, ll val,int size)
{
	for (int i = 0; i < size; i++)
		for (int j = 0; j < size; j++)
			relayDistance[No][i][j] = val;
}
void copyMatrix(int from, int to, int size)
{
	for (int i = 0; i < size; i++) {
		for (int j = 0; j < size; j++) {
			relayDistance[to][i][j] = relayDistance[from][i][j];
		}
	}
}
void init()
{
	for(int i=0;i<4;i++)
		setMatrix(i, INF, MAXN);
	vertices.clear();
	memset(edges, 0, sizeof(edges));
	memset(verticesMatch, 0xff, sizeof(verticesMatch));
}
void input()
{
	int length, place1, place2;
	for (int i = 0; i < T; i++) {
		scanf("%d %d %d", &length, &place1, &place2);
		edges[i] = Edge(place1, place2, length);
		vertices.insert(place1);
		vertices.insert(place2);
	}
	set<int >::iterator it;
	int j = 0;
	for (it = vertices.begin(); it != vertices.end(); it++) 
		verticesMatch[*it] = j++;
	graphSize = vertices.size();
}
void rebuild()
{
	for (int i = 0; i < T; i++) {
		int u = edges[i].u;
		int v = edges[i].v;
		int uu = verticesMatch[u];
		int vv = verticesMatch[v];
		assert(uu >= 0 && vv >= 0);
		ll weight = edges[i].length;
		relayDistance[0][uu][vv] = relayDistance[0][vv][uu] = weight;
	}
}
void calculate(int deustNo, int binstNo, int pozNo)
{
	setMatrix(pozNo, INF, graphSize);
	for (int i = 0; i < graphSize; i++) {
		for (int j = 0; j < graphSize; j++) {
			for (int k = 0; k < graphSize; k++) {
				relayDistance[pozNo][i][j] = min(relayDistance[pozNo][i][j], relayDistance[deustNo][i][k] +
					relayDistance[binstNo][k][j]);
			}
		}
	}
}
void solve()
{
	int temp = N;
	int bit = 0;
	copyMatrix(0, 3, graphSize);
	temp--;
	while (temp > 0) {
		if (temp & 0x1) {
			copyMatrix(3, 2, graphSize);
			calculate(0, 2, 3);
		}
		calculate(0, 0, 1);
		copyMatrix(1, 0, graphSize);
		temp >>= 1;
	}
	printf("%lld\n", relayDistance[3][verticesMatch[S]][verticesMatch[E]]);
}
int main()
{
	while (scanf("%d %d %d %d", &N, &T, &S, &E) != EOF) {
		init();
		input();
		rebuild();
		solve();
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值