试题编号: | 201609-2 |
试题名称: | 火车购票 |
时间限制: | 1.0s |
内存限制: | 256.0MB |
问题描述: | 问题描述 请实现一个铁路购票系统的简单座位分配算法,来处理一节车厢的座位分配。 输入格式 输入的第一行包含一个整数n,表示购票指令的数量。 输出格式 输出n行,每行对应一条指令的处理结果。 样例输入 4 样例输出 1 2 样例说明 1) 购2张票,得到座位1、2。 评测用例规模与约定 对于所有评测用例,1 ≤ n ≤ 100,所有购票数量之和不超过100。 |
java:(100分)
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
LinkedList[] queue = new LinkedList[20];
for(int i = 0; i < queue.length; i++) {
queue[i] = new LinkedList();
for(int j = 1; j <= 5; j++) {
queue[i].add(5*i+j);
}
}
for(int i = 0; i < n; i++) {
int p = sc.nextInt();
boolean flag = true;
for(int j = 0; j < queue.length; j++) {
if(queue[j].size() >= p) {
for(int k = 0; k < p; k++) {
System.out.print(queue[j].pop()+" ");
}
flag = false;
break;
}
}
if(flag) {
for(int j = 0; j < queue.length && flag; j++) {
while(queue[j].size() != 0) {//用!queue[j].isEmpty()也可以
System.out.print(queue[j].pop()+" ");
p--;
if(p == 0) {//这里记得打括号,不然会90分 报运行错误
flag = false;
break;
}
}
}
}
System.out.println();
}
}
}
c++:
#include <iostream>
#include <queue>
using namespace std;
queue<int> mp[21];
int N;
int main(void){
for(int i=1,j=1;i<=20;i++)
{
mp[i].push(j++);
mp[i].push(j++);
mp[i].push(j++);
mp[i].push(j++);
mp[i].push(j++);
}
cin>>N;
int num;
for(int i=0;i<N;i++)
{
cin>>num;
bool ok=false;
for(int row=1;row<=20;row++)
{
if(mp[row].size()>=num)
{
for(int j=0;j<num;j++)
{
cout<<mp[row].front()<<' ';
mp[row].pop();
}
ok=true;
break;
}
}
if(!ok)
{
for(int row=1;row<=20&&num>0;row++)
{
while(num>0&&!mp[row].empty())
{
cout<<mp[row].front()<<' ';
mp[row].pop();
num--;
}
}
}
cout<<endl;
}
return 0;
}
法二:
#include <iostream>
using namespace std;
int a[100]={0};
int b[20]={5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5};
void f(int row,int ps){
int pos=row*5;
do{
if(a[pos]==0){
a[pos]=1;
b[pos/5]--;
cout<<pos+1<<" ";
ps--;
if(ps==0) break;
}
pos++;
}while(true);
}
int main()
{
int n,dp;cin>>n;
for(int i=0;i<n;i++){
cin>>dp;
int row;
for(row=0;row<20;row++)
if(b[row]>=dp) break;
if(row!=20)
f(row,dp);
else
f(0,dp);
cout<<endl;
}
return 0;
}