标签:in touch hdu 5361 优先队列的dij 并查集优化
1 5 2 0 0 0 1 3 1 1 0 5 1 1 1 1 1
0 2 1 1 -1HintIf you need a larger stack size, please use #pragma comment(linker, "/STACK:102400000,102400000") and submit your solution using C++.
题意:有n个点站成一排,相邻距离为1,每个点 i 可以联系上距离自己 x 的点并且花费Ci,其中Li<=x<=Ri,从点1开始,求联系到每个点的最少费用。
思路:边太多,不可能建完边后再求最短路,感觉有点像隐式图,然后就是巧妙用到Dijstra,需要注意到的就是,这里是每个点有权值而不是边,那么dist[i]表示从1到 i 的花费再加上点 i 的花费,这样每个点就只会被更新一次,更新后在以后就不会再次被更新了,这里用到并查集把已经更新的点得father指向还没被更新的点。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <map>
#include <stack>
#include <functional>
#include <vector>
#include <set>
#include <queue>
#pragma comment (linker,"/STACK:102400000,102400000")
#define pi acos(-1.0)
#define eps 1e-6
#define lson rt<<1,l,mid
#define rson rt<<1|1,mid+1,r
#define FRE(i,a,b) for(i = a; i <= b; i++)
#define FREE(i,a,b) for(i = a; i >= b; i--)
#define FRL(i,a,b) for(i = a; i < b; i++)
#define FRLL(i,a,b) for(i = a; i > b; i--)
#define mem(t, v) memset ((t) , v, sizeof(t))
#define sf(n) scanf("%d", &n)
#define sff(a,b) scanf("%d %d", &a, &b)
#define sfff(a,b,c) scanf("%d %d %d", &a, &b, &c)
#define pf printf
#define DBG pf("Hi\n")
typedef __int64 ll;
using namespace std;
const ll INF = 1LL << 60; //要大点
#define mod 1000000009
const int maxn = 200010;
const int MAXN = 2005;
const int MAXM = 200010;
const int N = 1005;
typedef pair<ll,int>Pir;
ll L[maxn],R[maxn],C[maxn],dist[maxn];
int n,father[maxn];
void init()
{
for (int i=0;i<=n+5;i++)
{
father[i]=i;
dist[i]=INF;
}
}
int find_father(int x)
{
if (x!=father[x])
father[x]=find_father(father[x]);
return father[x];
}
void solve()
{
dist[1]=C[1];
priority_queue<Pir,vector<Pir>,greater<Pir> >Q;
Q.push(make_pair(dist[1],1));
while (!Q.empty())
{
Pir st=Q.top(); Q.pop();
int u=st.second;
for (int i=-1;i<=1;i+=2)
{
int l=u+i*L[u];
int r=u+i*R[u];
if (l>r) swap(l,r);
l=max(1,l);
l=min(l,n+1);
if (l>r) continue;
for (int v=l;;v++)
{
v=find_father(v);
if (v<=0||v>n||v>r) break;
if (dist[v]>dist[u]+C[v])
{
dist[v]=dist[u]+C[v];
Q.push(make_pair(dist[v],v));
}
father[find_father(v)]=find_father(v+1);
}
}
}
printf("0");
for (int i=2;i<=n;i++)
{
if (dist[i]>=INF)
printf(" -1");
else
printf(" %I64d",dist[i]-C[i]);
}
printf("\n");
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("C:/Users/lyf/Desktop/IN.txt","r",stdin);
#endif
int i,j,t;
scanf("%d",&t);
while (t--)
{
scanf("%d",&n);
for (i=1;i<=n;i++)
scanf("%I64d",&L[i]);
for (i=1;i<=n;i++)
scanf("%I64d",&R[i]);
for (i=1;i<=n;i++)
scanf("%I64d",&C[i]);
init();
solve();
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
In Touch (hdu 5361 优先队列的Dij + 并查集优化)
标签:in touch hdu 5361 优先队列的dij 并查集优化
原文地址:http://blog.csdn.net/u014422052/article/details/47376273