bzoj1752 [Usaco2005 qua]Til the Cows Come Home

Bessie返家最短路径算法
描述了如何利用单源最短路算法帮助Bessie以最快速度返回牛棚的故事。

Description

Bessie is out in the field and wants to get back to the barn to get as much sleep as possible before Farmer John wakes her for the morning milking. Bessie needs her beauty sleep, so she wants to get back as quickly as possible. Farmer John's field has N (2 <= N <= 1000) landmarks in it, uniquely numbered 1..N. Landmark 1 is the barn; the apple tree grove in which Bessie stands all day is landmark N. Cows travel in the field using T (1 <= T <= 2000) bidirectional cow-trails of various lengths between the landmarks. Bessie is not confident of her navigation ability, so she always stays on a trail from its start to its end once she starts it. Given the trails between the landmarks, determine the minimum distance Bessie must walk to get back to the barn. It is guaranteed that some such route exists.

Input

* Line 1: Two integers: T and N * Lines 2..T+1: Each line describes a trail as three space-separated integers. The first two integers are the landmarks between which the trail travels. The third integer is the length of the trail, range 1..100.

Output

* Line 1: A single integer, the minimum distance that Bessie must travel to get from landmark N to landmark 1.

Sample Input


5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100

INPUT DETAILS:

There are five landmarks.

Sample Output


90

OUTPUT DETAILS:

Bessie can get home by following trails 4, 3, 2, and 1.

这题各种单源最短路都能过

#include<cstdio>
#include<cstring>
int n,m,x,y,z,cnt,t,w=1;
int head[10001];
struct edge{
	int to,next,v;
}e[50001];
int q[50001];
bool mark[50001];
int dist[50001];
inline void ins(int u,int v,int w)
{
	e[++cnt].v=w;
	e[cnt].to=v;
	e[cnt].next=head[u];
	head[u]=cnt;
}
void insert(int u,int v,int w)
{
	ins(u,v,w);
	ins(v,u,w);
}
inline int read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
inline void spfa()
{
	q[1]=1;
	mark[1]=1;
	dist[1]=0;
	while (t<w)
	{
		int now=q[++t];
		for (int i=head[now];i;i=e[i].next)
		  if (dist[now]+e[i].v<dist[e[i].to])
		  {
		  	dist[e[i].to]=dist[now]+e[i].v;
		  	if (!mark[e[i].to])q[++w]=e[i].to;
		  }
		mark[now]=0;
	}
}
int main()
{
	m=read();n=read();
	memset(dist,127/3,sizeof(dist));
	for(int i=1;i<=m;i++)
	  {
		x=read();y=read();z=read();
		insert(x,y,z);
	  }
	spfa();
	printf("%d",dist[n]);
}


转载于:https://www.cnblogs.com/zhber/p/4036054.html

### 关于 BZOJ1728 Two-Headed Cows (双头牛) 的算法解析 此问题的核心在于如何通过有效的图论方法解决给定约束下的最大独立集问题。以下是详细的分析和解答。 #### 问题描述 题目要求在一个无向图中找到最大的一组节点集合,使得这些节点之间满足特定的颜色匹配条件。具体来说,每条边连接两个节点,并附带一种颜色标记(A 或 B)。对于任意一条边 \(u-v\) 和其对应的颜色 \(c\),如果这条边属于最终选取的子集中,则必须有至少一个端点未被选入该子集或者两端点均符合指定颜色关系。 #### 解决方案概述 本题可以通过 **二分枚举 + 图染色验证** 来实现高效求解。核心思想如下: 1. 假设当前最优解大小为 \(k\),即尝试寻找是否存在一个大小为 \(k\) 的合法子集。 2. 枚举每一个可能作为起点的节点并将其加入候选子集。 3. 对剩余部分执行基于 BFS/DFS 的图遍历操作,在过程中动态调整其他节点的状态以确保整体合法性。 4. 如果某次试探能够成功构建符合条件的大规模子集,则更新答案;反之则降低目标值重新测试直至收敛至最佳结果。 这种方法利用了贪心策略配合回溯机制来逐步逼近全局最优点[^1]。 #### 实现细节说明 ##### 数据结构设计 定义三个主要数组用于记录状态信息: - `color[]` : 存储每个顶点所分配到的具体色彩编号; - `used[]`: 表示某个定点是否已经被处理过; - `adjList[][]`: 记录邻接表形式表示的原始输入数据结构便于后续访问关联元素。 ##### 主要逻辑流程 ```python from collections import deque def check(k, n): def bfs(start_node): queue = deque([start_node]) used[start_node] = True while queue: u = queue.popleft() for v, c in adjList[u]: if not used[v]: # Assign opposite color based on edge constraint 'c' target_color = ('B' if c == 'A' else 'A') if color[u]==c else c if color[v]!=target_color and color[v]!='?': return False elif color[v]=='?': color[v]=target_color queue.append(v) used[v] =True elif ((color[u]==c)==(color[v]==('B'if c=='A'else'A'))): continue return True count=0 success=True for i in range(n): if not used[i]: temp_count=count+int(color[i]=='?' or color[i]=='A') if k<=temp_count: color_copy=color[:] if bfs(i): count=temp_count break else : success=False return success n,m=list(map(int,input().split())) colors=[['?']*m]*n for _ in range(m): a,b,c=input().strip().split() colors[int(a)-1].append((int(b),c)) low ,high,res=0,n,-1 while low<=high: mid=(low+high)//2 color=['?']*n used=[False]*n if check(mid,n): res=mid low=mid+1 else : high=mid-1 print(res) ``` 上述代码片段展示了完整的程序框架以及关键函数 `check()` 的内部运作方式。它接受参数 \(k\) 并返回布尔值指示是否有可行配置支持如此规模的选择[^2]。 #### 复杂度分析 由于采用了二分查找技术缩小搜索空间范围再加上单轮 DFS/BFS 时间复杂度 O(V+E),总体性能表现良好适合大规模实例运行需求。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值