蓝桥杯/NYOJ 990 蚂蚁感冒 .

来源:互联网 发布:nginx 域名绑定子目录 编辑:程序博客网 时间:2024/05/17 06:42

题目地址:http://acm.nyist.net/JudgeOnline/problem.php?pid=990

以前写蓝桥杯的时候不会写,看了刘汝佳的UVA 10881后发现好简单

就是把蚂蚁当作不会回头,只是直接穿过

那么两个蚂蚁穿过后就会让另外一只也感冒

所以只需要判断一下能穿过的蚂蚁的数量


对于一开始感冒蚂蚁的位置p,假设p>0

p会碰到右边所有向左走的蚂蚁,

那些在右边被p碰到的蚂蚁会去碰到它左边所有向右走的蚂蚁


结论(p>0):

1. ans+=p左边与p正负相反的蚂蚁数量

2.如果1的蚂蚁存在,ans+=p右边与p正负一样的蚂蚁


p<0结论也类似


AC代码如下:

#include <iostream>#include <cstdio>#include <algorithm>#include <cstring>using namespace std;int ant[50+5];bool cmp(int i,int j){return abs(i)<abs(j);}int main(int argc, char const *argv[]){int n;while(cin>>n){int a;for(int i=0;i<n;++i)scanf("%d",&ant[i]);a=ant[0];sort(ant,ant+n,cmp);bool ok=false;int ans=1;int p=find(ant,ant+n,a)-ant;int d=a>0?1:-1;for(int i=p+d;i<n&&i>=0;i+=d)if(ant[i]*a<0) ok=true,ans++;if(ok)for(int i=p-d;i<n&&i>=0;i-=d)if(ant[i]*a>0) ans++;cout<<ans<<endl;}return 0;}


0 0
原创粉丝点击