点时间刷刷题吧
TimeLimit:1000MS MemoryLimit:32768MB
64-bit integer IO format:
%I64d
Problem Description
说粗来泥萌可能不信,Home_W喜欢的公主被魔王抓走了!!!
Home_W当然是要去救公主的,但是魔塔的结构很复杂,Home_W需要聪明的你帮助他,找到一条最省魔力的路径去打到魔王,拯救公主。
魔塔有n个传送阵,编号从1-n,而且魔塔有很多层,最多不超过n层,编号从1-n。
任意相连的两层里的传送阵都可以互相传送(比如第二层有传送阵 1 2,第三层有传送阵 3 4 ,那么 1-3,1-4,2-3,2-4都可以互相传送,这些传送费用都为C)
传送当然需要消耗魔力了,相连两层之间传送消耗的魔力 为C,另外Home_W还得知,有额外的m条传送通道(双向)
Home_W初始位置为编号为1的传送阵,魔王在编号为n的传送阵上。
Input
输入第一行一个T表示T组测试数据
第一行三个数n,m(0<=n,m<=1e5),c(1<=c<=1e3) n个传送阵,m个额外的传送通道,相连两层之前传送花费为c
接下来一行n个数a1-an,表示第i个传送阵在ai层
接下来m行,每行三个数u,v,w 表示从传送阵u传送到v需要花费w的魔力 (1<=w<=1e4)
Output
对于第i组样例输出
Case #i: ans
ans为消耗的最小魔力,不存在输出-1
SampleInput
2 3 3 3 1 3 2 1 2 1 2 3 1 1 3 3 3 3 3 1 3 2 1 2 2 2 3 2 1 3 4
SampleOutput
Case #1: 2 Case #2: 3 第一个样例:传送阵1 - 2 花费为1 传送阵2 - 3 花费为1 传送阵1 - 3 花费为3 第一层到第二层 互相传送的传送阵 1 - 3 花费为 3 第二层到第三层 互相传送的传送阵 3 - 2 花费为 3 答案是 1-2-3 花费为2
如果没有层与层直接可以任意传送,这题就是个普通的最短路,但是有这个条件,所以需要将一层抽象为一个点,这一层的所有点与这个抽象的点联通,这些边的长度为0,但如果建双向的边,那一堆边为0的点就会进入死循环,所以这时候就需要拆点
将一个点拆为两个点,一个点入,一个点出
#include <cstdio>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <vector>
#include <stack>
#include <cstring>
#include <queue>
#include <set>
#include <string>
#include <map>
#include <climits>
#include <ctime>
#define PI acos(-1)
using namespace std;
typedef long long ll;
typedef double db;
const int maxn = 2e5 + 5;
const int mod = 1e9 + 7;
const int INF = 1e8 + 5;
const ll inf = 1e15 + 5;
const db eps = 1e-8;
int cnt, head[maxn]; ll dis[maxn];
struct Edge
{
int v; ll w; int next;
bool operator < (const Edge &rhs) const
{
return w > rhs.w;
}
} e[maxn*4];
void add(int u, int v, int co)
{
e[cnt].v = v;
e[cnt].w = co;
e[cnt].next = head[u];
head[u] = cnt++;
}
void init()
{
cnt = 0;
memset(head, -1, sizeof(head));
}
void dij(int s, int len)
{
priority_queue<Edge> pq;
for (int i = 1; i <= len; i++)
dis[i] = inf;
bool vis[maxn] = {0};
dis[s] = 0;
pq.push((Edge){s, 0, 0});
while (!pq.empty())
{
Edge tmp = pq.top(); pq.pop();
if (vis[tmp.v]) continue;
vis[tmp.v] = 1;
for (int i = head[tmp.v]; ~i; i = e[i].next)
{
Edge u = e[i];
if (dis[u.v] > dis[tmp.v] + u.w)
{
dis[u.v] = dis[tmp.v] + u.w;
pq.push((Edge){u.v, dis[u.v], 0});
}
}
}
}
int a[maxn];
void solve()
{
int n, m, c; cin >> n >> m >> c;
init();
for (int i = 1; i <= n; i++)
{
scanf("%d", a + i);
add(i, a[i] + n, 0);
if (a[i] < n) add(a[i]+1+n, i, c);
if (a[i] > 1) add(a[i]-1+n, i, c);//拆点 同一个集合里
}
for (int i = 1; i <= m; i++)
{
int u, v, w; scanf("%d%d%d", &u, &v, &w);
add(u, v, w); add(v, u, w);
}
dij(1, n*2);
if (dis[n] == inf) dis[n] = -1;
cout << dis[n] <<endl;
}
int main()
{
int t = 1, cas = 1;
//freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
scanf("%d", &t);
while(t--)
{
printf("Case #%d: ", cas++);
solve();
}
return 0;
}