手打代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 #include <bits/stdc++.h> #pragma GCC optimize(3,"Ofast" ,"inline" ) using namespace std;int a[13 ][5 ];map<long long ,bool > m; struct node { int x[13 ],path[18 ]={},step; bool operator () (node la,node lb) { int sla=0 ,slb=0 ; for (int i=1 ;i<=12 ;i++){ if (la.x[i]!=1 )sla++; if (lb.x[i]!=1 )slb++; } return sla/2 +la.step>slb/2 +lb.step; } }n,t; long long num (int x[]) { long long s=0 ; for (int i=1 ;i<13 ;i++) s=s*10 +x[i]; return s; } void bfs (node n) { priority_queue<node,vector<node>,node> q; q.push (n); long long b; while (!q.empty ()){ t=n=q.top (); q.pop (); for (int i=1 ;i<13 ;i++){ n.x[a[i][n.x[i]]]++; if (n.x[a[i][n.x[i]]]==5 ) n.x[a[i][n.x[i]]]=1 ; n.x[i]++; if (n.x[i]==5 ) n.x[i]=1 ; b=num (n.x); if (m[b]){ n=t; continue ; } m[b]=1 ; n.path[n.step++]=i; if (b==111111111111 ){ cout<<n.step<<"\n" ; for (int j=0 ;j<n.step;j++) cout<<n.path[j]<<" " ; return ; } q.push (n); n=t; } } } int main () { for (int i=1 ;i<=12 ;i++) for (int j=0 ;j<5 ;j++) cin>>a[i][j]; auto start = chrono:: system_clock:: now () .time_since_epoch () .count (); for (int i=1 ;i<=12 ;i++) n.x[i]=a[i][0 ]; m[num (n.x)]=1 ; bfs (n); auto duration = chrono:: system_clock:: now () .time_since_epoch () .count () -start; cerr <<"time=" <<duration /1e9 << endl; return 0 ; }
AI分析 十二个开关的转动问题:每次按下一个开关,会让它自身和相邻开关的档位变化,目标是把十二个开关全部转到第一档,求最少步数与操作序列。代码把十二个开关的状态压成一个十进制数用于判重,再使用带估价函数的优先队列做启发式搜索。估价函数取仍然不在目标位置的开关数量的一半,因为一次操作最多修正两个,这个下界能有效引导搜索方向。每次转移复制当前状态、更新受影响的位置、记录路径并压入队列。这实际上是 A 星算法的雏形,用较小的状态空间换取可接受的运行时间。
由于状态总数有限,判重用的映射表会占一定内存,可以用数组代替 map 提速。估价函数必须不超过真实剩余步数,否则会破坏最优性,这是写启发式搜索最重要的纪律。