蓝桥杯——错误票据

题目

某涉密单位下发了某种票据,并要在年终全部收回。
因为工作人员疏忽,在录入ID号的时候发生了一处错误,造成了某个ID断号,另外一个ID重号。
你的任务是通过编程,找出断号的ID和重号的ID。
假设断号不可能发生在最大和最小号。
要求程序首先输入一个整数N(N<100)表示后面数据行数。
接着读入N行数据。
每行数据长度不等,是用空格分开的若干个(不大于100个)正整数(不大于100000)
每个整数代表一个ID号。
每张票据有唯一的ID号。全年所有票据的ID号是连续的,但ID的开始数码是随机选定的。
要求程序输出1行,含两个整数m n,用空格分隔。
其中,m表示断号ID,n表示重号ID
例如:
用户输入:
2
5 6 8 11 9
10 12 9

则程序输出:
7 9

再例如:
用户输入:
6
164 178 108 109 180 155 141 159 104 182 179 118 137 184 115 124 125 129 168 196
172 189 127 107 112 192 103 131 133 169 158
128 102 110 148 139 157 140 195 197
185 152 135 106 123 173 122 136 174 191 145 116 151 143 175 120 161 134 162 190
149 138 142 146 199 126 165 156 153 193 144 166 170 121 171 132 101 194 187 188
113 130 176 154 177 120 117 150 114 183 186 181 100 163 160 167 147 198 111 119

则程序输出:
105 120

解题

这题的关键在于将每一行的输入数据取出来,问题在于我们并不知道每一行会有多少个数据,使用常规的scanf接收数据这题就算废了。这里可以分为几个步骤。

  1. 这里可以把每一行的数据看作字符串,把每一行的数据以字符串形式接收
  2. 用字符串的分割将字符串分割成只含数值不含空格的小串
  3. 把小串的字符串类型转成数值型
#include<iostream>                     //标准输入输出操作
#include<sstream>                      //数值转换操作
#include<algorithm>                    //sort算法

using namespace std;

const int Max = 10000;
int line = 0;
int data[Max];

void s2i(string &temp,int &num)              //类型转换
{
	stringstream ss;
	ss<<temp;
	ss>>num;	
}

int main(){
	scanf("%d",&line);
	getchar();
	int i = 0;
	int index = 0;
	for(i=0;i<line;i++)
	{
		string s;
		getline(cin,s);
		istringstream iss(s);	
		string temp;
		while(getline(iss,temp,' '))
		{
			s2i(temp,data[index++]);
		}
	}
	sort(data,data+index);
	int a=0,b=0;
	for(i=0;i<index;i++)
	{
		if(data[i]==data[i-1])
			a = data[i];
		if(data[i]==data[i-1]+2)
			b = data[i]-1;
	}
	printf("%d %d",a,b);	
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/weixin_44078014/article/details/107657120