蓝桥杯刷题-04-岛屿个数-DFS


cpp 复制代码
#include <iostream>
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=2e5+10;
typedef pair<int,int>pii;

map<pii, int>st;//记录从{x,y}的距离是多少
int a[N];//存储原始路径


vector<pii>edge[N];//存图

// s表示你要求的路径的起点
// v表示你要求的路径的终点
//u表示你当前走到了哪个点
//father表示你当前这个点的父亲节点是谁。避免重复走造成死循环。
// sum表示从s走到u的路径花费总和。
bool dfs(int s,int u,int father,int v,int sum)
{
  if(u==v){
    st[{s,v}]=sum;
    st[{v,s}]=sum;
    return true;
  }
  for(int i=0;i<edge[u].size();i++)
  {
    int son=edge[u][i].first;
    if(son==father)
      continue;
    int w=edge[u][i].second;

    if(dfs(s,son,u,v,sum+w))
      return true;

  }
  return false;
}


void sovle()
{
  int n,k;
  cin>>n>>k;
  for(int i=0;i<n-1;i++)
  {
    int x,y,t;
    cin>>x>>y>>t;
    edge[x].push_back({y,t});
    edge[y].push_back({x,t});
  }
  for(int i=0;i<k;i++)
    cin>>a[i];
  
  int ans=0;

  //总花费
  for(int i=0;i<k-1;i++)
  {
    dfs(a[i],a[i],-1,a[i+1],0);
    ans+=st[{a[i],a[i+1]}];
  }

  //跳过某个景点的花费
  for(int i=0;i<k;i++)
  {
    int tmp=ans;
    if(i==0)
      tmp-=st[{a[i],a[i+1]}];
    else if(i==k-1)
      tmp-=st[{a[i-1],a[i]}];
    else
    {
      tmp-=st[{a[i-1],a[i]}];
      tmp-=st[{a[i],a[i+1]}];
      dfs(a[i-1],a[i-1],-1,a[i+1],0);
      tmp+=st[{a[i-1],a[i+1]}];

    }
    cout<<tmp<<" ";
  }
}


signed main()
{
  // DFS遍历
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int t=1;
  //cin>>t;
  while(t--)
  sovle();

  return 0;
}
相关推荐
qq_459234421 天前
【题库】| 商用密码应用安全性评估从业人员考核题库(四十)
职场和发展·密码学·学习方法·考核·商用密码·商用密码应用安全性评估·密评
敲敲了个代码1 天前
[特殊字符] 空数组的迷惑行为:为什么 every 为真,some 为假?
前端·javascript·react.js·面试·职场和发展
独自破碎E1 天前
【DFS】BISHI76 迷宫寻路
算法·深度优先
代码无bug抓狂人1 天前
C语言之单词方阵——深搜(很好的深搜例题)
c语言·开发语言·算法·深度优先
码农幻想梦1 天前
3472. 八皇后(北京大学考研机试题目)
考研·算法·深度优先
诚思报告YH1 天前
视频面试软件市场洞察:2026 - 2032年复合年均增长率(CAGR)为10.3%
面试·职场和发展
重生之后端学习1 天前
74. 搜索二维矩阵
开发语言·数据结构·算法·职场和发展·深度优先
tyb3333331 天前
leetcode:吃苹果和队列
算法·leetcode·职场和发展
觅特科技-互站1 天前
实测:接入陌讯Skills后Copilot任务完成率↑63%、调试耗时↓90%
线性回归·深度优先·copilot
Pitiless-invader1 天前
MySQL 相关知识及面试问题汇总
面试·职场和发展