http://acm.hdu.edu.cn/showproblem.php?pid=1535
题意:某演员雇佣一些志愿者去一些站台做志愿活动,每一天他们要从起点CSS安检后到所有站台,安检后的所有路程就会有花费,且路程是单向的。做完活动又要返回CSS安检,结束一天的活动。求问这个演员最少需要花费多少。
思路:题意比较难理解,应该是阅读水平不够。从起点到所有点,再从所有点到起点的最小花费。前者好求,后者点数太多,不能一个一个求。考虑到这些点到起点和起点到这些点的距离相同,但是方向不一样,于是就反向建边。用邻接矩阵敲完才发现点数过多,只好又用邻接表敲一次。。
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <queue>
using namespace std;
typedef long long LL;
const int N = 1000005;
const int INF = 0x3f3f3f3f;
int dis[N], pos, pos0, head[N], head0[N], n;
bool vis[N];
struct Edge
{
int to, w, next;
}edge[N], edge0[N];
void add(int u, int v, int w)
{
edge[pos] = (struct Edge){v, w, head[u]};
head[u] = pos++;
}
void add0(int u, int v, int w)
{
edge0[pos0] = (struct Edge){v, w, head0[u]};
head0[u] = pos0++;
}
void spfa1(int s)
{
memset(vis, false, sizeof(vis));
queue<int>que;
for(int i = 1; i <= n; i++)
dis[i] = INF;
dis[s] = 0;
vis[s] = true;
que.push(s);
while(!que.empty())
{
int u = que.front();
que.pop();
vis[u] = false;
for(int i = head[u]; i != -1; i = edge[i].next)
{
int v = edge[i].to;
if(dis[u]+edge[i].w<dis[v])
{
dis[v] = dis[u]+edge[i].w;
if(!vis[v])
{
vis[v] = true;
que.push(v);
}
}
}
}
}
void spfa2(int s)
{
memset(vis, false, sizeof(vis));
queue<int>que;
for(int i = 1; i <= n; i++)
dis[i] = INF;
dis[s] = 0;
vis[s] = true;
que.push(s);
while(!que.empty())
{
int u = que.front();
que.pop();
vis[u] = false;
for(int i = head0[u]; i != -1; i = edge0[i].next)
{
int v = edge0[i].to;
if(dis[u]+edge0[i].w<dis[v])
{
dis[v] = dis[u]+edge0[i].w;
if(!vis[v])
{
vis[v] = true;
que.push(v);
}
}
}
}
}
void init()
{
pos = pos0 = 0;
memset(head, -1, sizeof(head));
memset(head0, -1, sizeof(head0));
}
int main()
{
// freopen("in.txt", "r", stdin);
int t, m, u, v, w;
scanf("%d", &t);
while(t--)
{
init();
scanf("%d%d", &n, &m);
for(int i = 1; i <= m; i++)
{
scanf("%d%d%d", &u, &v, &w);
add(u, v, w);
add0(v, u, w);
}
int sum = 0;
spfa1(1);
for(int i = 1; i <= n; i++)
sum+=dis[i];
spfa2(1);
for(int i = 1; i <= n; i++)
sum+=dis[i];
printf("%d\n", sum);
}
return 0;
}