牛客寒假算法基础集训营1 C. 小a与星际探索(dp或者各种姿势)

版权声明:欢迎转载,若转载,请标明出处,如有错误,请指点,也欢迎大佬们给出优化方法 https://blog.csdn.net/Charles_Zaqdt/article/details/86600996

题目链接:https://ac.nowcoder.com/acm/contest/317/C

       这道题本质上是一道dp题,但是dijkstra或者搜索都可以过,没什么说的,只贴dp和搜索的呆码吧,dij写的太丑了,而且也不知道为什么姿势不对就会内存超限。


AC代码(dp):

#include <bits/stdc++.h>
#define maxn 4005
using namespace std;
int dp[10005],pre[maxn],a[maxn];
int n;

int main()
{
  scanf("%d",&n);
  for(int i=1;i<=n;i++){
    scanf("%d",&a[i]);
  }
  int cnt = 0;
  for(int i=2;i<n;i++){
    if(a[1] > a[i] && a[i] > a[n]) pre[cnt++] = a[i];
  }
  dp[a[1] ^ a[n]] = 1;
  for(int i=0;i<cnt;i++){
    for(int j=5000;j>=0;j--){
      dp[j] |= dp[j ^ pre[i]];
    }
  }
  int pos;
  for(int i=5000;i>=0;i--){
    if(dp[i]){
      pos = i;
      break;
    }
  }
  if(a[1] <= a[n])puts("-1");
  else printf("%d\n", pos);
  return 0;
}

AC代码(bfs):

#include <bits/stdc++.h>
using namespace std;
int n,ans;
bool vis[5005];
int pre[3005];
  
void bfs(){
  queue<int> q;
  memset(vis, false, sizeof(vis));
  q.push(pre[1]);
  vis[pre[1]] = true;
  while(!q.empty()){
    int now = q.front();
    q.pop();
    for(int i=2;i<=n;i++){
      if(now > pre[i]){
        int nex = (now ^ pre[i]);
        if(i == n) ans = max(ans, nex);
        if(!vis[nex] && i < n){
          vis[nex] = true;
          q.push(nex);
        }
      }
    }
  }
}
  
int main()
{
  scanf("%d",&n);
  for(int i=1;i<=n;i++){
    scanf("%d",&pre[i]);
  }
  ans = 0;
  bfs();
  printf("%d\n", ans > 0 ? ans : -1);
  return 0;
}

猜你喜欢

转载自blog.csdn.net/Charles_Zaqdt/article/details/86600996