我想做一个程序,统计同时有多少客人在场。所有客人都有到达和离开时间。我已经统计了客人的最大数量,它可以在它达到最大值时给我一次。我要的是出现最大客人数时的所有时间间隔
我曾尝试使用重叠方法来完成此操作,但效果不佳,可能是因为它比较了列表中太多或太少的值。我有两个列表,到达和退出,当它写在我的控制台应用程序上时,我会在其中添加值。
我尝试在一个列表中添加来自 time 和 time2 的时间并对其进行排序,但它为某些测试输入添加了太多值。
int max = 1; int count = 1;
int i = 1; int j = 0;
long time = arrival[0]; long time2= dep[0];
while (i < n1 && j < n1) // n1 is the length of the input integer
{
if (arrival[i] < dep[j])
{
count++;
if (count >= max)
{
max = count;
time = arrival[i];
time2= dep[j];
}
// possible location of console.writeline(time1 + time2)
// somewhere here I would add time and time2 to a new list
i++;
}
else
{
count--;
j++;
}
} Console.WriteLine(max); Console.WriteLine(time1 + " " + time2);
假设我的输入是 5 位客人,间隔为:(12,30)、(18,25)、(25,40)、(13,15) 和 (32,36),想要的结果将是
2//最大人数
13 15//每个间隔换行
18 30
32 36
但我无法让它工作,它只显示 32-36。如果我将 console.writeline 放在可能的位置,它会给我:13-15、18-25、25-30、32-36。对于具有更多重复项的其他测试输入(例如 0 到 5 在列表中出现不止一次),它给了我太多的间隔。
最佳答案
制作数组或结构列表,其中包含所有客人的到达和离开时间以及 +1/-1
表示事件类型的标志(+1 表示到达)。
按时间字段排序列表。在 tie put arrival event first 的情况下,如果你想在零间隔内注册两个客人(一个进入,另一个同时离开),否则先离开 - 似乎是你的情况。
制作Count = 0
和 MaxCount
.
遍历列表,将标志字段添加到 Count
.
Count
的值在每个事件之后表示房间中的任务数。
Guests (12,30), (18,25), (25,40), (13,15) and (32,36)
Events 12;1 13;1 15;-1 18;1 25;-1 25;1 30;-1 32;1 36;-1 40;-1
Count 0 1 2 1 2 1 2 1 2 1 0
^ x ^ x ^ x ^ x
Max intervals (^-x)
当 Count
达到 MaxCount
- 开始新的输出间隔,当它变为 MaxCount - 1
时- 完成该间隔并将其添加到 OutList
当 Count
超过 MaxCount
- 清除 OutList
, 使 MaxCount - Count
并开始新的输出间隔
最后输出MaxCount
和间隔从 OutList
关于c# - 根据客人数量的最大计数合并重叠间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56196919/