bzoj 1001 分类: bzoj 2015-06-27 16:05 24人阅读 评论(0) 收藏
平面图最大流,看到数据范围我就怂了。
先构造平面图的对偶图,然后求最短路即可。
时间复杂度:
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <vector>
#include <utility>
#include <iostream>
#include <algorithm>
const int maxm = 1005, maxn = 1005;
const int maxnode = ((maxn-1)*(maxm-1)<<1);
const int maxe = maxnode * 3, INF = 1<<30;
struct Edge
{
int v, w, next;
Edge(){}
Edge(int v,int w,int next):v(v),w(w),next(next){}
}edge[maxe];
int n, m, node, S, T;
int head[maxnode], el = 0;
int read()
{
int x = 0;char c = getchar();
while(c < '0' || c > '9') {c = getchar();}
while(c >= '0' && c <= '9'){x = (x<<3) + (x<<1) + (c-'0'); c = getchar();}
return x;
}
void write(long long x)
{
static char s[20];int sl = 0;
while(x) s[++sl] = x%10 + '0',x /= 10;
if(!sl) {putchar('0');return;}
while(sl) putchar(s[sl--]);
}
void NewEdge(int u,int v,int w)
{
edge[++el] = Edge(v, w, head[u]), head[u] = el;
}
void Build()
{
int now, last, w;
now = 2, last = 1 - ((m-1)<<1);
for(int i = 1; i <= n; i++)
for(int j = 1; j < m; j++)
{
w = read();
if(i == 1)
NewEdge(S, now, w), NewEdge(now, S, w);
else if(i == n)
NewEdge(last, T, w), NewEdge(T, last, w);
else
NewEdge(last, now, w), NewEdge(now, last, w);
now += 2, last += 2;
}
now = 1, last = 0;
for(int i = 1; i < n; i++)
for(int j = 1; j <= m; j++)
{
w = read();
if(j == 1)
NewEdge(T, now, w), NewEdge(now, T, w);
else if(j == m)
NewEdge(last, S, w), NewEdge(S, last, w);
else
NewEdge(last, now, w), NewEdge(now, last, w);
if(j != m) now += 2, last += 2;
}
now = 2, last = 1;
for(int i = 1; i < n; i++)
for(int j = 1; j < m; j++)
{
w = read();
NewEdge(last, now, w), NewEdge(now, last, w);
now += 2, last += 2;
}
}
typedef std::pair<long long,int> Heapnode;
#define Root_Min std::vector<Heapnode>,std::greater<Heapnode>
std::priority_queue<Heapnode, Root_Min> heap;
bool hash[maxnode];
long long dist[maxnode];
long long Dijstra()
{
for(int i = 1; i <= node; i++) dist[i] = INF;
dist[S] = 0, heap.push(std::make_pair(0, S));
while(!heap.empty())
{
int t = heap.top().second;
heap.pop();
if(hash[t]) continue;
hash[t] = true;
if(t == T) break;
for(int i = head[t], p; i ; i = edge[i].next)
if(!hash[p = edge[i].v])
{
long long tmp = dist[t] + edge[i].w;
if(tmp < dist[p])
dist[p] = tmp, heap.push(std::make_pair(tmp, p));
}
}
return dist[T];
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("bzoj1001.in","r",stdin);
freopen("bzoj1001.out","w",stdout);
#endif
n = read(), m = read(), node = ((n-1)*(m-1)<<1) + 2;
S = node - 1, T = node;
Build(), write(Dijstra());
#ifndef ONLINE_JUDGE
fclose(stdin);
fclose(stdout);
#endif
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。