建立平面图的对偶图,把最小割转化成最短路问题
Dijkstra算法堆优化
(被输入顺序搞WA了好几次T_T)
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 #include <queue> 5 6 const int maxN=502; 7 const int maxV=maxN*maxN; 8 const int inf=0x3f3f3f3f; 9 10 struct Edge 11 { 12 int to,next; 13 int dist; 14 void assign(int t,int n,int d) 15 { to=t; next=n; dist=d; } 16 }; 17 18 Edge elist[maxV*4]; 19 int head[maxV]; 20 int ecnt; 21 int N; 22 int dest; 23 24 void initEdge() 25 { 26 memset(head,-1,sizeof(head)); 27 ecnt=0; 28 } 29 30 inline void addEdge(int from,int to,int dist) 31 { 32 elist[ecnt].assign(to,head[from],dist); 33 head[from]=ecnt++; 34 } 35 36 void input() 37 { 38 scanf("%d",&N); 39 dest=N*N+1; 40 initEdge(); 41 int w; 42 for(int j=0;j<=N;j++) 43 for(int i=1;i<=N;i++) 44 { 45 scanf("%d",&w); 46 if(!j) addEdge(0,i,w); 47 else if(j==N) addEdge(N*N+i-N,dest,w); 48 else addEdge(N*j+i-N,N*j+i,w); 49 } 50 for(int j=1;j<=N;j++) 51 for(int i=0;i<=N;i++) 52 { 53 scanf("%d",&w); 54 if(!i) addEdge(N*j+1-N,dest,w); 55 else if(i==N) addEdge(0,N*j,w); 56 else addEdge(N*j+i+1-N,N*j+i-N,w); 57 } 58 for(int j=0;j<=N;j++) 59 for(int i=1;i<=N;i++) 60 { 61 scanf("%d",&w); 62 if(!j || j==N) continue; 63 else addEdge(N*j+i,N*j+i-N,w); 64 } 65 for(int j=1;j<=N;j++) 66 for(int i=0;i<=N;i++) 67 { 68 scanf("%d",&w); 69 if(!i || i==N) continue; 70 else addEdge(N*j+i-N,N*j+i+1-N,w); 71 } 72 } 73 74 struct Vertex 75 { 76 int idx; 77 int dist; 78 Vertex() {} 79 Vertex(int i,int d):idx(i),dist(d) {} 80 bool operator < (const Vertex& other) const 81 { return this->dist > other.dist; } 82 }; 83 84 int dist[maxV]; 85 int open[maxV]; 86 std::priority_queue<Vertex> que; 87 88 int dijkstra() 89 { 90 memset(dist,0x3f,sizeof(dist)); 91 memset(open,1,sizeof(open)); 92 dist[0]=0; open[0]=false; 93 int cur=0; 94 while(cur!=dest) 95 { 96 for(int e=head[cur];e!=-1;e=elist[e].next) 97 { 98 int& to=elist[e].to; 99 int& len=elist[e].dist; 100 if(open[to] && dist[to]>dist[cur]+len) 101 { 102 dist[to]=dist[cur]+len; 103 que.push(Vertex(to,dist[to])); 104 } 105 } 106 Vertex vt; 107 do { vt=que.top(); que.pop(); } 108 while(!open[vt.idx]); 109 cur=vt.idx; 110 open[cur]=false; 111 } 112 return dist[dest]; 113 } 114 115 int main() 116 { 117 input(); 118 printf("%d\n",dijkstra()); 119 return 0; 120 }
时间: 2024-10-05 02:39:52