标签:des style blog color io os ar java for
题目大意:给你一个N*N的图让你到达所有的“.”点,“#”不能通过,有m组每组有一个入口,一个出口,入口可以传送到出口,不知道经过m组的先后顺序,让你求出走过所有的“.”的最小时间。
思路:先bfs出来所有的m之间的最短距离,然后dp[j][i] 表示,在j状态下开始第i步的最小路程,枚举找到一个最小的dp[1<<m - 1][i],就是最短距离,否则输出“-1”。
5 4 ....# ...#. ..... ..... ..... 2 3 1 4 1 2 3 5 2 3 3 1 5 4 2 1
7
#include <set> #include <map> #include <queue> #include <math.h> #include <vector> #include <string> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <iostream> #include <algorithm> #define LL __int64 using namespace std; const int INF = 0x3f3f3f3f; const int maxn = 20; struct node { int x0, y0; int x1, y1; } f[maxn]; struct node1 { int x, y; }; int cnt; char str[maxn][maxn]; bool vis[maxn][maxn]; int dis[maxn][maxn]; int d[maxn][maxn]; int dx[] = {0, 1, -1, 0}; int dy[] = {1, 0, 0, -1}; int dp[1<<16][maxn]; int mp[maxn][maxn]; int n, m; void spfa(int s, int t) { for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { vis[i][j] = false; d[i][j] = INF; } } node1 tmp; tmp.x = s; tmp.y = t; vis[s][t] = true; queue<node1>fp; fp.push(tmp); d[s][t] = 0; while(!fp.empty()) { tmp = fp.front(); fp.pop(); for(int i = 0; i < 4; i++) { int x = tmp.x+dx[i]; int y = tmp.y+dy[i]; if(x <= n && x >= 1 && y <= n && y >= 1 && mp[x][y]) { if(vis[x][y]) continue; d[x][y] = d[tmp.x][tmp.y]+1; vis[x][y] = true; node1 tmx; tmx.x = x; tmx.y = y; fp.push(tmx); } } } } int main() { while(~scanf("%d %d",&n, &m)) { memset(mp, 0, sizeof(mp)); for(int i = 1; i <= n; i ++) { scanf("%s", str[i]+1); for(int j = 1; j <= n; j++) if(str[i][j] == '.') mp[i][j] = 1; } for(int i = 1; i <= m; i++) scanf("%d %d %d %d",&f[i].x0, &f[i].y0, &f[i].x1, &f[i].y1); for(int i = 1; i <= m; i++) { spfa(f[i].x1, f[i].y1); for(int j = 1; j <= m; j++) { if(i == j) { dis[i][j] = 0; continue; } dis[i][j] = d[f[j].x0][f[j].y0]; } } memset(dp, INF, sizeof(dp)); for(int i = 1; i <= m; i++) dp[1<<(i-1)][i] = 0; for(int i = 2; i <= m; i++) { for(int j = 0; j < (1<<m); j++) { int sum = 0; for(int k = 0; k < m; k++) if(j&(1<<k)) sum++; if(sum != i-1) continue; for(int k = 0; k < m; k++) { if((j&(1<<k)))continue; for(int tt = 1; tt <= m; tt++) { int ans = dp[j][tt]+dis[tt][k+1]; dp[j|(1<<k)][k+1] = min(dp[j|(1<<k)][k+1], ans); } } } } int ans = INF; for(int i = 1; i <= m; i++) ans = min(ans, dp[(1<<m)-1][i]); if(ans == INF) { puts("-1"); continue; } printf("%d\n",ans); } return 0; }
标签:des style blog color io os ar java for
原文地址:http://blog.csdn.net/xu12110501127/article/details/40157231