题目链接:http://acm.acmcoder.com/showproblem.php?pid=1535
题意:有向图,求源点到各个点最短路径和+各个点到源点最短路径和。
spfa求单源最短路径,求各个点到源点最短路径翻转边。
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <string>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <map>
using namespace std;
const int MAXN = 2000010;
const int INF = 1e9+10;
struct
{
int a, b, c;
}Map[MAXN];
int t;
int n, m, a, b, c;
struct Edge
{
int v;
int cost;
Edge(int _v = 0, int _cost = 0)
{
v = _v;
cost = _cost;
}
};
vector<Edge> E[MAXN];
void addedge(int u, int v, int cost)
{
E[u].push_back(Edge(v, cost));
}
bool vis[MAXN];
int cnt[MAXN];
int dist[MAXN];
void SPFA(int start, int n)
{
memset(vis, false, sizeof(vis));
for (int i = 1; i <= n; i++) dist[i] = INF;
vis[start] = true;
dist[start] = 0;
queue<int> que;
while (!que.empty()) que.pop();
que.push(start);
memset(cnt, 0, sizeof(cnt));
cnt[start] = 1;
while (!que.empty())
{
int u = que.front(); que.pop();
vis[u] = false;
for (int i = 0; i<E[u].size(); i++)
{
int v = E[u][i].v;
if (dist[v]>dist[u] + E[u][i].cost)
{
dist[v] = dist[u] + E[u][i].cost;
if (!vis[v])
{
vis[v] = true;
que.push(v);
if (++cnt[v] > n) return;
}
}
}
}
}
int main()
{
scanf("%d",&t);
while (t--)
{
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
E[i].clear();
for (int i = 1; i <= m; i++)
{
scanf("%d%d%d", &Map[i].a, &Map[i].b, &Map[i].c);
addedge(Map[i].a, Map[i].b, Map[i].c);
}
int ans = 0;
SPFA(1, n);
for (int i = 1; i <= n; i++)
ans += dist[i];
for (int i = 1; i <= n; i++)
E[i].clear();
for (int i = 1; i <= m; i++)
addedge(Map[i].b, Map[i].a, Map[i].c);
SPFA(1, n);
for (int i = 1; i <= n; i++)
ans += dist[i];
printf("%d\n", ans);
}
return 0;
}
时间: 2024-11-25 02:44:22