【问题标题】:C++ Movie SeatingC++ 电影座位
【发布时间】:2012-09-15 13:23:35
【问题描述】:

这几天我一直在发疯,试图解决这个座位分配问题,想知道是否有人可以帮助我。

说明说:

假设一组 n 名学生一起来上课(或看电影),并且恰好有 n 个座位在 1 排连续可用。给定 m 对座位的偏好,你要确定有多少学生想要就座来统计偏好。

输入

输入将仅来自键盘。输入将包含多个测试用例。每个测试用例以两个整数 0

输出

每个测试用例的输出是一行,其中包含满足所有输入约束的组的可能座位安排数量。

示例输入

3 1

0 1 -2

3 0

0 0

样本输出

2

6

#include <vector>
#include <algorithm>
#include <string>
#include <iostream>
#include <iterator>

using namespace std;


struct Preference
{
int a;
int b;                     //Struct with three preferences
int c;
};


int main()
{
int a,b,c,students,numpref;
int count = 0;

vector<Preference> prefs;              //Vector with struct to store preferences
Preference case1;

cout<<"Enter number of students and preferences: ";
cin>>students>>numpref;          //Total Number of students and preferences are entered



for(int i = 0; i<=numpref; i++)
{
cin>>case1.a>>case1.b>>case1.c;
prefs.push_back(case1);                  //Stores preferences in vector
cout<<endl;
}

vector<int> v2(a);               //Second vector created to store list of students

sort(v2.begin(), v2.end());

while(next_permutation(v2.begin(), v2.end()))  
                                  //Finds all permutations of student seating
{


}


system("PAUSE");
return 0;
}

我知道它不完整,但我主要是想弄清楚如何将每行偏好与正确的排列进行比较,然后计算结果。我考虑过获取用户输入的向量中每个元素的位置(例如:示例中的 0,1),并检查找到的每个排列是否有 0 和 1,它们之间至少有 2 个座位。但这行不通。

【问题讨论】:

  • 你为什么说它不起作用?太慢了?
  • 好吧,每次我尝试使用 if 语句来比较向量中两个变量之间的距离时,结果都不会正确。
  • 你是否创建了一个函数来计算两个特定学生之间的距离?
  • 我尝试使用 myvector.at() 函数来尝试计算两个学生之间的距离,但无法使其正常工作,因此我认为这不是一个好的解决方案。例如:我尝试执行类似“if(v2.at(a) - v2.at(b) >= c)”的操作。但这显然永远不会返回正确的答案。
  • 你需要 vector::at 的逆函数,你需要一个函数来返回特定学生的索引,而不是特定索引处的学生。

标签: c++ stl vector permutation next


【解决方案1】:

你认为可以工作的算法,但是很慢。我在你不完整的代码中发现了一些错误。

for(int i = 0; i<=numpref; i++) 

我觉得应该是这样的

for(int i = 0; i<numpref; i++) 

【讨论】:

  • 感谢您的提示。关于如何将偏好与排列进行比较的任何建议?我遇到的问题是试图弄清楚每次所有用户的偏好都与排列匹配时计数,然后将结果存储在计数器中。
  • @Stephen Frankie 如果您不考虑效率,对于每个排列,您可以计算一个矩阵,a(i,j)=distance(i,j),然后您可以使用枚举每个偏好这个矩阵。我认为这很容易编写代码。
  • 嗯..谢谢你的推荐。我会尝试编写一些代码。我是一名新程序员,所以其中许多概念对我来说也很新。
猜你喜欢
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-24
  • 1970-01-01
  • 1970-01-01
  • 2021-11-02
相关资源
最近更新 更多