题目大意:每组数据给出8个数字,可能正可能负。要求最后将这8个数字按照数字绝对值从小到大的排序。排序的规则是让某个数字a邀请另一个数字b跳舞,这样a就可以插到b的左边或是右边,a能邀请b跳舞,则a* b <0 ,且a+b要是素数。题目问给出一组数据问能否通过邀请跳舞来排序,能的话就输出最少的邀请次数,否则输出-1.
解题思路:这题一开始竟然想着dfs,但是后面发现,这样的判断树可以是无限大,因为可以a邀请完b,然后b在邀请a,这样一来一回有可能保持原样。所应该用隐式图遍历,因为这里的不能让相同的状态重复执行,并且要求的是最少次数,隐式图是bfs遍历,正好是先找到终态即路径最短。这里对于一个状态需要从头开始每个数字都考虑一下,能否和其他的数字跳舞,邀请成功后就要选择站到左边还是右边。
注意:插入到某个数的左边,右边情况还需要根据跳舞的两个数的位置来定,要细心。
代码:
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <algorithm> using namespace std; const int MAXN = 1000005; const int N = 8; int state[MAXN][N], head[MAXN], next[MAXN], dist[MAXN]; bool cmp (const int& a, const int& b) { if (abs(a) < abs(b)) return true; return false; } bool is_prime (int n) { for (int i = 2; i <= sqrt(n); i++) if (n % i == 0) return false; return true; } int hash (int rear) { int sum = 0; for (int i = 0; i < N; i++) sum = sum * 10 + abs(state[rear][i]); return sum % MAXN; } bool trytoinsert (int rear) { int p = hash (rear); int u = head[p]; while (u) { if (memcmp(state[rear], state[u], sizeof (state[u])) == 0) return false; u = next[u]; } next[rear] = head[p]; head[p] = rear; return true; } //插入到某个数的左边或是右边 p1要插入的数的位置, p2被插队的那个数的位置,dir = 0插入到左边,dir = 1插入到右边
void change (int p1, int p2, int front, int& rear, int dir) { int temp = state[front][p1]; memcpy (state[rear], state[front], sizeof (state[front])); if (p1 < p2) { if (dir == 0) { for (int i = p1 + 1; i < p2; i++) state[rear][i - 1] = state[rear][i]; state[rear][p2 - 1] = temp; } else { for (int i = p1 + 1;i <= p2; i++) state[rear][i - 1] = state[rear][i]; state[rear][p2] = temp; } } if (p1 > p2) { if (dir == 1) { for (int i = p1; i > p2; i--) state[rear][i] = state[rear][i - 1]; state[rear][p2 + 1] = temp; } else { for (int i = p1; i >= p2; i--) state[rear][i]= state[rear][i - 1]; state[rear][p2] = temp; } }//判断该状态是否重复,不重复就入队 if (trytoinsert(rear)) { dist[rear] = dist[front] + 1; rear++; } } int bfs () { int front, rear; front = 1; rear = 2; memset (dist, 0, sizeof (dist)); memset (head, 0, sizeof(head)); while (front < rear) { if (memcmp (state[0], state[front], sizeof (state[0])) == 0) return dist[front]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (i != j && state[front][i] * state[front][j] < 0 && is_prime (abs (state[front][i]) + abs (state[front][j]))) { change (i, j, front, rear, 0); change (i, j, front, rear, 1); } } } front++; } return -1; } int main () { int t = 0; while (scanf ("%d", &state[1][0]), state[1][0]) { for (int i = 1; i < N; i++) scanf ("%d", &state[1][i]); memcpy(state[0], state[1], sizeof (state[1])); sort (state[0], state[0] + N, cmp); printf ("Case %d: %d\n", ++t, bfs()); } return 0; }
11198 - Dancing Digits(BFS + hash判重)
时间: 2024-10-24 05:47:56