P8611 [蓝桥杯 2014 省 AB] 蚂蚁感冒

网站:https://www.luogu.com.cn/problem/P8611

题目:

这个题目核心思路:
定义ant:位置和方向(true:往右跑)
找到第一个的位置
如果第一个向左跑,那么先搜索左边,统计左边向右跑的个数,添加到ans,因为所有的向右跑都会传递过去,有几个向右跑就会有几个染病
向左跑完之后同理搜索右边的向左跑,同上;
如果第一个向右跑,则是法一反向执行就行
代码:

#include<iostream>
#include<vector>
#include<algorithm>
#include<math.h>
#include<sstream>
#include<string>
#include<string.h>
#include<iomanip>
#include<map>
#include<queue>
#include<limits.h>
#include<climits>
using namespace std;
typedef long long ll;

int n;
struct ant
{
	int id;
	bool toward;//true:right
}antlst[80];
bool toward[80] = { 0 };
bool cmp(ant a, ant b)
{
	return a.id < b.id;
}
int main()
{
	cin >> n;
	int xx;
	int first = 0;
	int firstid = 0;
	int ans = 1;
	for (int i = 0; i < n; i++)
	{
		cin >> xx;
		if (i == 0)first = abs(xx);
		antlst[i].id = abs(xx);
		antlst[i].toward = (xx > 0) ? 1 : 0;
	}
	sort(antlst, antlst + n, cmp);
	for (int i = 0; i < n; i++)
		if (antlst[i].id == first)
		{
			firstid = i;
			break;
		}
	for (int i = 0; i < n; i++)
		toward[i] = antlst[i].toward;
	int firsttoward = toward[firstid];
	//如果向左,那么先查左边,因为最后不一定向右
	if(firsttoward == 0)
	{
		int to_right = 0;
		bool next = firsttoward;
		for (int i = 0; i < firstid; i++)
		{
			if (toward[i] == 1)
				to_right++;
		}
		if (to_right > 0)
		{
			ans += to_right;
			next = 1 - firsttoward;
		}
		to_right = 0;
		if(next == 1)
			for (int i = firstid + 1; i < n; i++)//查右边
			{
				if (toward[i] == 0)
					to_right++;
			}
		if (to_right > 0)
		{
			ans += to_right;
		}
	}
	else
	{
		int to_right = 0;
		bool next = firsttoward;
		for (int i = firstid + 1; i < n; i++)//查右边
		{
			if (toward[i] == 0)
				to_right++;
		}
		if (to_right > 0)
		{
			ans += to_right;
			next = 1 - firsttoward;
		}
		to_right = 0;
		if (next == 0)
			for (int i = 0; i < firstid; i++)
			{
				if (toward[i] == 1)
					to_right++;
			}
		if (to_right > 0)
		{
			ans += to_right;
		}
	}
	cout << ans;
	return 0;
}

没有debug,最爽的一集

posted on 2024-03-12 10:29  WHUStar  阅读(3)  评论(0编辑  收藏  举报