题目链接:
http://codeforces.com/contest/821/problem/D
题意:
有一个n*m的矩形上面有k盏灯,每盏灯占一个格子。只能走有灯的格子,但是当在一个原始就有灯的地方可以花费1使一行或者一列变亮以供行走。现在要求你从左上(1,1)走到右下(n,m),求最小花费。
题解:
这题可以将k个点看做图中的点,由于站在一个初始亮的点上可以将一行或一列变亮,所以我们可以在这个点上,点亮相邻的一行或一列,然后再到相邻行列上的任意点。这样就能够想到了再引入行和列作为图中的点,然后以k个点k行k列作为图的顶点建图。从一个点到相邻行列花费是1,反向花费是0,然后跑一遍最短路就可以了。
#include<bits/stdc++.h>
using namespace std;
#define inf 0x7fffffff
#define ll long long
#define ull unsigned long long
const int mod = 1e4+7;
const ll INF = 1e18;
typedef pair<int, int>P;
const double eps = 1e-6;
const int maxn = 6e5+5;
struct edge
{
int to, cost;
edge(){}
edge(int to, int cost):to(to), cost(cost){}
};
vector<edge>G[maxn];
int d[maxn];
P p[maxn];
map<P, int> mp;
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
void dijkstra(int s)
{
priority_queue<P, vector<P>, greater<P> >q;
fill(d, d+maxn, inf);
d[s] = 0;
q.push(P(0, s));
while(!q.empty()) {
P p = q.top();
q.pop();
int v = p.second;
if(d[v] < p.first) continue;
for(int i=0; i<G[v].size(); i++) {
edge e = G[v][i];
if(d[e.to] > d[v] + e.cost) {
d[e.to] = d[v] + e.cost;
q.push(P(d[e.to], e.to));
}
}
}
}
int main()
{
int n, m, k;
cin >> n >> m >> k;
int dd = 1e4+5;
mp.clear();
for(int i=1; i<=k; i++) {
int r, c;
scanf("%d%d", &r, &c);
//从点到相邻边
G[i].push_back(edge(r+dd, 1));
G[i].push_back(edge(c+2*dd, 1));
G[i].push_back(edge(r+1+dd, 1));
G[i].push_back(edge(r-1+dd, 1));
G[i].push_back(edge(c+1+2*dd, 1));
G[i].push_back(edge(c-1+2*dd, 1));
//从相邻边到点
G[r+dd].push_back(edge(i, 0));
G[c+2*dd].push_back(edge(i, 0));
G[r+1+dd].push_back(edge(i, 0));
G[r-1+dd].push_back(edge(i, 0));
G[c+1+2*dd].push_back(edge(i, 0));
G[c-1+2*dd].push_back(edge(i, 0));
p[i] = P(r, c);
mp[P(r, c)] = i;
}
for(int i=1; i<=k; i++) {
for(int j=0; j<4; j++) {
int x = p[i].first + dx[j];
int y = p[i].second + dy[j];
//相邻点
if(mp.find(P(x, y))!=mp.end()) {
//printf("%d--\n", i);
G[i].push_back(edge(mp[P(x, y)], 0));
}
}
}
//puts("-");
if(mp.find(P(n, m))==mp.end()) {
G[n+dd].push_back(edge(k+1, 0));
G[m+2*dd].push_back(edge(k+1, 0));
}
dijkstra(mp[P(1, 1)]);
int ans;
if(mp.find(P(n, m))==mp.end()) {
ans = d[k+1];
}
else {
ans = d[mp[P(n, m)]];
}
if(ans == inf)
ans = -1;
cout << ans << endl;
//cout << d[3] << endl;
}