一道好的NOIp题目,在赛场上总能用许多算法A掉。比如这道和关押罪犯。

题目传送门

法一:tarjan在有向图中跑最小环

有人从别人口中得知自己信息,等效于出现了一个环。于是 这就变成了一个有向图tarjan强连通分量的板子题。

 #include<cstdio>
#include<algorithm>
#include<stack>
#define maxn 200090 using namespace std; int n,y,tot,ans=,dfs_clock,scc_cnt,tong[maxn],dfn[maxn],low[maxn],head[maxn],scc[maxn];
stack<int>s;
struct node{
int to,next;
}edge[maxn]; void add(int x,int y)
{
edge[++tot].to=y;
edge[tot].next=head[x];
head[x]=tot;
} void dfs(int p)
{
dfn[p]=low[p]=++dfs_clock;
s.push(p);
for(int i=head[p];i;i=edge[i].next)
{
int y=edge[i].to;
if(!dfn[y])
{
dfs(y);
low[p]=min(low[p],low[y]);
}
else if(!scc[y]) low[p]=min(low[p],dfn[y]);
}
if(dfn[p]==low[p])
{
scc_cnt++;
while()
{
int x=s.top();
s.pop();
scc[x]=scc_cnt;
if(x==p) break;
}
}
} int main()
{
scanf("%d",&n);
for(int i=;i<=n;i++)
scanf("%d",&y),add(i,y);
for(int i=;i<=n;i++)
{
if(!dfn[i]) dfs(i);
tong[scc[i]]++;
}
for(int i=;i<=scc_cnt;i++) if(tong[i]>&&tong[i]<ans) ans=tong[i];
printf("%d\n",ans);
return ;
}

法二:拓扑排序

图中可能会出现很多环,求最小的一个。我们跑一遍拓扑排序后,那些不曾入到队列中的点就是成环的点。于是我们可以边拓扑排序边标记最后找到那些在环上的点,从他们出发分别求出环的大小进行比较。

 #include<cstdio>
#include<algorithm>
#include<queue> using namespace std; int n,x,ans=,cnt,tot;
int du[],head[],vis[],flag[];
struct node{
int to,next;
}edge[];
queue<int>q; void add(int x,int y)
{
edge[++tot].next=head[x];
edge[tot].to=y;
head[x]=tot;
} void topo()
{
for(int i=;i<=n;i++)
if(!du[i]) q.push(i),flag[i]=;
while(!q.empty())
{
int u=q.front();q.pop();
for(int i=head[u];i;i=edge[i].next)
{
int v=edge[i].to;
if(--du[v]==) q.push(v),flag[v]=;
}
}
} void dfs(int x)
{
vis[x]=,cnt++;
for(int i=head[x];i;i=edge[i].next)
{
int y=edge[i].to;
if(vis[y]) return ;
dfs(y);
}
} int main()
{
scanf("%d",&n);
for(int i=;i<=n;i++)
scanf("%d",&x),add(i,x),du[x]++;
topo();
for(int i=;i<=n;i++)
if((!flag[i])&&(!vis[i]))
{
cnt=;
dfs(i);
ans=min(ans,cnt);
}
printf("%d",ans);
return ;
}

法三:并查集

https://anyway.blog.luogu.org/solution-p2661

最新文章

  1. 直播推流之blibli和拉流LFLiveKit
  2. JS高程3.基本概念(3)
  3. IOS-WebViewJavascriptBridge使用说明
  4. 关于java中MessageFormat.format中单引号问题
  5. 20161127-emmagee
  6. ASP.NET 获取不同frame中的控件
  7. 2013 - Lost connection to MySQL server at &#39;reading initial communication packet&#39; 错误解决
  8. Sharepoint学习笔记—习题系列--70-573习题解析 -(Q54-Q56)
  9. Radar之获取排列的UITexture数组
  10. c#抽象类相关
  11. javascript跑马灯抽奖
  12. linux进程间通信--无名管道
  13. 【HDOJ】2157 How many ways??
  14. Android canvas rotate():平移旋转坐标系至任意原点任意角度-------附:android反三角函数小结
  15. 【USACO 2.2.1】序言页码
  16. 安装升级System.Web.Optimization.dll
  17. WAS集群系列(2):数据库连接低级错误——网络连接问题
  18. 我们的java基础到底有多差 一个视频引发的感想
  19. 为什么在STM32F429工程配置中需要预先定义USE_STDPERIPH_DRIVER和STM32F429_439xx?
  20. POJ 2001 Shortest Prefixes(字典树)

热门文章

  1. 【转载】究竟啥才是互联网架构&ldquo;高可用&rdquo;
  2. plsql 无需配置客户端连接.
  3. iOS之UI--使用SWRevealViewController 实现侧边菜单功能详解实例
  4. C++结构体中使用函数与类中使用函数小结
  5. LeetCode(27)题解:Remove Element
  6. Mac使用小结
  7. DOM操作一
  8. Elasticsearch分布式安装启动失败
  9. Python小练习_数据库表数据导出到excel
  10. 西交校赛 F. GZP and Poker