这道题困扰我一学期了,大意是求多源最短路径并要求每条路径的长度恰好为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;
}