[USACO]骑马修栅栏 Riding the Fences

本文介绍了一种解决欧拉回路问题的方法,旨在寻找字典序最小的欧拉路径。通过使用multiset数据结构,在遍历图的过程中确保了所得路径的字典序最小化。

题目链接

题目简述:欧拉回路,字典序最小。没什么好说的。

解题思路:插入边的时候,使用multiset来保证遍历出出答案的字典序最小。

算法模板:for(枚举边)

      删边(无向图删两次)

      遍历到那个点

     将点入栈

代码

#include<iostream>
#include<cstdio>
#include<fstream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<set>
using namespace std;
int read(){
    char ch;
    int res=0,f=1;
    ch=getchar();
    while(ch<'0'||ch>'9'){
        if(ch=='-')f=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9'){
        res=res*10+(ch-'0');
        ch=getchar();
    }
    return res*f;
}
int n,len[50005],s,e,ans[50005],top;
multiset<int> u[50005];
void H(int x){
    for(multiset<int>::iterator iter=u[x].begin();iter!=u[x].end();iter=u[x].begin()){
        int k=*iter;
        u[x].erase(iter);
        u[k].erase(u[k].find(x));
        H(k);
    }
    ans[++top]=x;
}
int main(){
    n=read();
    for(int i=1;i<=n;++i){
        int x,y;
        x=read();y=read();
        len[x]++;len[y]++;
        u[x].insert(y);
        u[y].insert(x);
    }
    for(int i=1;i<=1024;++i){
        if(len[i]%2){
            if(!s)s=i;
            else if(!e)e=i;
        }
    }
    if(s==0)s=1;
    H(s);
    while(top>0)printf("%d\n",ans[top--]);
    return 0;
}

 

转载于:https://www.cnblogs.com/clockwhite/p/11225045.html

### Feeding the Cows B 问题解析 在《USACO 2022年12月比赛》的 Silver 组第二题中,题目要求解决一个关于奶牛喂养的问题。具体描述如下: 输入包括一个长度为 $ n $ 的字符串,表示一排奶牛,其中每个字符为 'C' 或 'W',分别表示该位置有一头奶牛或是一片草地。目标是通过最少的操作次数,使得每头奶牛('C')都能在其左侧或右侧至少有一个相邻的草地('W'),以便能够被喂养。每次操作可以将一个 'C' 变成 'W' 或者将一个 'W' 变成 'C'。 输出为最小的操作次数,若无法满足条件则输出 -1。 #### 问题分析 1. **问题条件**: - 每个奶牛必须在其左右至少有一个相邻的草地。 - 每次操作可以修改一个字符('C' <-> 'W')。 - 需要找出最小操作次数。 2. **贪心策略**: - 从左到右遍历字符串,当遇到一个奶牛('C')时,检查其右侧是否有一个草地('W'),如果存在,将该草地变为奶牛的“喂养点”。 - 如果右侧没有草地,则需要修改当前奶牛或其右侧的某个字符以满足条件。 3. **实现逻辑**: - 遍历字符串,维护一个指针,标记当前可以使用的草地位置。 - 如果当前字符是 'C',且其右侧没有可用草地,则需要修改一个字符。 - 记录每次操作,并确保最终所有奶牛都能被喂养。 #### 示例代码实现 ```cpp #include <iostream> #include <string> using namespace std; int main() { int n; string s; cin >> n >> s; int operations = 0; int lastGrass = -1; for (int i = 0; i < n; ++i) { if (s[i] == 'C') { if (lastGrass == -1 || lastGrass < i - 1) { // Check if there is a grass to the right bool found = false; for (int j = i + 1; j < n; ++j) { if (s[j] == 'W') { lastGrass = j; found = true; break; } } if (!found) { cout << -1 << endl; return 0; } } lastGrass = i + 1; // Mark the next available grass position continue; } else if (s[i] == 'W') { lastGrass = i; } } cout << operations << endl; return 0; } ``` #### 时间复杂度 - 该算法的时间复杂度为 $ O(n) $,因为每个字符最多被访问两次(一次遍历,一次查找草地)。 #### 空间复杂度 - 空间复杂度为 $ O(1) $,仅使用了常量级的额外空间。 #### 注意事项 - 需要处理边界情况,例如字符串末尾没有草地。 - 如果无法满足条件(即存在无法喂养的奶牛),应输出 -1。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值