Why Did the Cow Cross the Road (B) \operatorname{Why\ Did\ the\ Cow\ Cross\ the\ Road\ (B)} Why Did the Cow Cross the Road (B)
题目链接: nowcoder 24078 \operatorname{nowcoder\ 24078} nowcoder 24078
题目
题目大意
一些母牛在一个路口左右横条,我们已近得知在从前往后某些时段某个奶牛的位置。
问你母牛横穿马路最少有多少次。(就是所有母牛横穿的次数加在一起)
样例输入
8
3 1
3 0
6 0
2 1
4 1
3 0
4 0
3 1
样例输出
3
样例解释
在此示例中,母牛 3 3 3 杂交两次:她首先出现在第 1 1 1 侧,然后出现在第 0 0 0 侧,然后又出现在第 1 1 1 侧。母牛 4 4 4 肯定杂交了一次。母牛 2 2 2 和 6 6 6 似乎没有杂交。
思路
这道题是一道小小的贪心。
题目要求最小跨越次数,就是尽可能让奶牛不要跨越。
那第一次出现某一只奶牛的位置时,我们就觉得它一开始就在那里,那就不用跨越。
如果后面有出现而且位置不同,那这个奶牛一定是跨越了,那就只能更改位置,答案加一。
然后最后输出答案即可。
代码
#include<cstdio>
using namespace std;
int n, x, y, cow[11], ans;
int main() {
for (int i = 1; i <= 10; i++) cow[i] = -1;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d %d", &x, &y);
if (cow[x] == -1) cow[x] = y;//原来没有记录过
else if (cow[x] != y) {//已经确定横穿了
cow[x] = y;
ans++;
}
}
printf("%d", ans);
return 0;
}