题目地址:http://acm.nyist.net/JudgeOnline/problem.php?pid=543
思路:队友教的我,能想到广搜,队友用了优先队列并且用visit数组标记已经到达的频道号
AC代码:
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <queue> #include <stack> #include <map> #include <cstring> #include <climits> #include <cmath> #include <cctype> const int inf = 0x7f7f7f7f;//2139062143 typedef long long ll; using namespace std; int a[15]; int visit[100];//标记已经走过的频道号 int start,end1; struct node { int loc; int step; friend bool operator < (node a,node b) { return a.step > b.step;//最小值优先 } }; int bfs() { priority_queue<node> pq; node now,next; now.loc = start; now.step = 0; visit[start] = 1; pq.push(now); while(!pq.empty()) { next = pq.top(); pq.pop(); if(next.loc == end1) { return next.step; } if(a[11])//频道号增加1 { now.loc = (next.loc + 1) % 100; now.step = next.step + 1; if(!visit[now.loc]) { visit[now.loc] = 1; pq.push(now); } } if(a[12])//频道号减少1 { now.loc = (next.loc - 1 + 100) % 100; now.step = next.step + 1; if(!visit[now.loc]) { visit[now.loc] = 1; pq.push(now); } } for(int i=0; i<10; i++)//到0-9的频道号 { if(a[i] && !visit[i]) { now.loc = i; now.step = next.step + 1; visit[now.loc] = 1; pq.push(now); } } for(int i=10; i<100; i++)//到10-99的频道号 { if(a[10] && a[i/10] && a[i%10] && !visit[i]) { now.loc = i; now.step = next.step + 3; visit[now.loc] = 1; pq.push(now); } } } return -1; } int main() { int t; scanf("%d",&t); while(t--) { memset(visit,0,sizeof(visit)); scanf("%d%d%d%d",&a[1],&a[2],&a[3],&a[11]); scanf("%d%d%d%d",&a[4],&a[5],&a[6],&a[12]); scanf("%d%d%d",&a[7],&a[8],&a[9]); scanf("%d%d",&a[10],&a[0]); scanf("%d%d",&start,&end1); int sum = bfs(); printf("%d\n",sum); } return 0; }
#include <stdio.h> #include <stdlib.h> int c[128]; int id(int x) { if(x < 0) return x+100; else return x%100; } int to(int x) { x = id(x); if(x/10==0) return c[x]; int a = x/10,b = x%10; if(!c['-'] || !c[a] || !c[b]) return 0; else return 3; } int min(int a,int b) { if(a==-1) return b; else return a<b ? a : b; } int main() { int z,a,b,ans; scanf("%d",&z); while(z--) { ans = -1; for(int i=1;i<=3;i++) scanf("%d",&c[i]); scanf("%d",&c['s']); for(int i=4;i<=6;i++) scanf("%d",&c[i]); scanf("%d",&c['x']); for(int i=7;i<=9;i++) scanf("%d",&c[i]); scanf("%d%d",&c['-'],&c[0]); scanf("%d%d",&a,&b); for(int i=1;i<100;i++) { if(c['s']) { if(id(b-i)==a) ans = min(ans,i); else if(to(b-i)) ans = min(ans,to(b-i)+i); } if(c['x']) { if(id(b+i)==a) ans = min(ans,i); else if(to(b+i)) ans = min(ans,to(b+i)+i); } } printf("%d\n",ans); } // system("pause"); return 0; }