算法笔记 3.1 简单模拟 练习题

A.剩下的树

有一个长度为整数L(1<=L<=10000)的马路,可以想象成数轴上长度为L的一个线段,起点是坐标原点,在每个整数坐标点有一棵树,即在0,1,2,…,L共L+1个位置上有L+1棵树。
现在要移走一些树,移走的树的区间用一对数字表示,如 100 200表示移走从100到200之间(包括端点)所有的树。
可能有M(1<=M<=100)个区间,区间之间可能有重叠。现在要求移走所有区间的树之后剩下的树的个数。

#include<bits/stdc++.h>
using namespace std;

int main()
{
    int l,m;
    while(scanf("%d %d",&l,&m)!=EOF)
	{
		if(l==0&&m==0)
		{
			break;
		}					
	int a[l+1];
	memset(a,1,sizeof(a));
	for(int i=0;i<m;i++)
	{
		int x,y;
		cin>>x>>y;
		for(int j=x;j<=y;j++)
		a[j]=0;		
	 } 
	 int sum=0;
    for(int i=0;i<=l;i++)
    {
    	if(a[i]) 
    	sum++;
	}
	cout<<sum<<endl;
  }
	return 0;
}

一开始打算计算两个区间的长度差,但是发现会重叠的话情况太多,所以最后选择巧妙利用数组表示,又简单又方便。


B. A+B

给定两个整数A和B,其表示形式是:从个位开始,每三位数用逗号","隔开。现在请计算A+B的结果,并以正常形式输出。

#include<bits/stdc++.h>
using namespace std;

long long int f(string a,int n)
{
	long long int sum=0;
	int j=1;
	for(int i=n-1;i>=0;i--)
	{
		if(a[i]>='0'&&a[i]<='9')
		{
			sum=sum+j*(a[i]-48);
			j=j*10;
		}
	}
	if(a[0]=='-')
	sum=(-1)*sum;
	return sum;
}

int main()
{
	string s1,s2;
    while(cin>>s1>>s2)
	{
		
		int l1=s1.length();
		int l2=s2.length();
		cout<<f(s1,l1)+f(s2,l2)<<endl;
    }
	return 0;
}

一开始以为考察大数加法,打算一位一位算加法,但是发现长度限制在longlong范围内,所以输入字符串,将字符串转为longlongint后直接加即可,注意有负号时要变成负数。

字符型数字转int型数字一定要-48


C. Shortest Distance

The task is really simple: given N exits on a highway which forms a simple cycle, you are supposed to tell the shortest distance between any pair of exits.

输入
Each input file contains one test case. For each case, the first line contains an integer N (in [3, 10 5 ^{5} 5]), followed by N integer distances D1 D2 … DN, where Di is the distance between the i-th and the (i+1)-st exits, and DN is between the N-th and the 1st exits. All the numbers in a line are separated by a space. The second line gives a positive integer M (<=10 4 {^4} 4), with M lines follow, each contains a pair of exit numbers, provided that the exits are numbered from 1 to N. It is guaranteed that the total round trip distance is no more than 10 7 {^7} 7.

#include<bits/stdc++.h>
using namespace std;

int main()
{
	int n;
	cin>>n;
    int a[n+1],distance[n+1];
    int sum=0;
    distance[0]=0;
    for(int i=1;i<=n;i++)
    {
    	cin>>a[i];
    	sum=sum+a[i];
    	distance[i]=distance[i-1]+a[i];
	}
	int m;
	cin>>m;
	while(m)
	{
		int x,y,Min;
		cin>>x>>y;
		if(x>y)
		Min=distance[x-1]-distance[y-1];
		else Min=distance[y-1]-distance[x-1];
		cout<<min(Min,(sum-Min))<<endl;
		m--;
	}
	return 0;
}

循环路径求最小,有两种情况:顺时针的距离,逆时针的距离。这样这道题的目的就明确为求两点间距离d和所有距离-d的最小值。如果每次都要求输入的两点间的距离,明显会超时,所以采用求出每个点与起点的距离,然后做差算两点间距离。

注意:下标表示的含义。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值