一份丑陋的代码献上

· · 题解

思路

思路就是一个十分普通的BFS,但是有三个维度,时间,第一个人的位置,第二个人的位置(时间是一个附带属性,不用加,但我懒),废话不多说,直接上代码。

#include<bits/stdc++.h>
using namespace std;
int t,n,m,c[2005],s[2005][2005],a,b;
map<int,set<int> >ma; 
struct node{
  int x,y,t;
};
void bfs(){
  queue<node>q;
  q.push({1,n,1});
  while(!q.empty()){
    node tmp = q.front();
    if (tmp.x == n && tmp.y == 1){
      cout << tmp.t - 1<< "\n";
      return;
      }
    q.pop();
    for (set<int>::iterator i = ma[tmp.x].begin();i != ma[tmp.x].end();i++){
      for (set<int>::iterator j = ma[tmp.y].begin();j != ma[tmp.y].end();j++){
        if(!s[*i][*j] && *i != *j && c[*i] != c[*j]){
          s[*i][*j] = tmp.t + 1,q.push({*i,*j,tmp.t + 1});
        }
        }
      }
  }
  cout << "-1\n";
}
int main(){
  for (cin >> t;t;t--){
    cin >> n >> m;
    for (int i = 1;i <= n;i++){
      cin >> c[i];
      }
    ma.clear(),fill(s[0],s[n + 1],0);
    for (int i = 1;i <= m;i++){
      cin >> a >> b,ma[a].insert(b),ma[b].insert(a);
    }
    bfs();
  }
} 

Ps:我用了一种十分神奇的存图法(值是set的map),似乎快亿点,不过遍历不能用auto,紧急复习了一下set遍历,而且为给老师看,压了亿点行,格式也不一样,请谅解。