本文整理汇总了C#中SortedDictionary.First方法的典型用法代码示例。如果您正苦于以下问题:C# SortedDictionary.First方法的具体用法?C# SortedDictionary.First怎么用?C# SortedDictionary.First使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SortedDictionary
的用法示例。
在下文中一共展示了SortedDictionary.First方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CalculateMedianSum
public static int CalculateMedianSum(int[] numbers)
{
int medianSum = 0;
var lowHeap = new SortedDictionary<int, int>();
var highHeap = new SortedDictionary<int, int>();
lowHeap.Add(numbers[0],0);
medianSum += numbers[0];
for (int index = 1; index < numbers.Length; index++)
{
int lowHeapMax = lowHeap.Last().Key;
int current = numbers[index];
// update heaps
if (current < lowHeapMax)
{
lowHeap.Add(current,0);
}
else
{
highHeap.Add(current, 0);
}
bool mayRequireBalancing = (index + 1)%2 == 0;
// balancing
if (mayRequireBalancing && lowHeap.Count != highHeap.Count)
{
if (lowHeap.Count > highHeap.Count)
{
lowHeapMax = lowHeap.Last().Key;
lowHeap.Remove(lowHeapMax);
highHeap.Add(lowHeapMax, 0);
}
else
{
int highHeapMin = highHeap.First().Key;
highHeap.Remove(highHeapMin);
lowHeap.Add(highHeapMin, 0);
}
}
// calculate median
if (lowHeap.Count >= highHeap.Count)
{
medianSum += lowHeap.Last().Key;
}
else
{
medianSum += highHeap.First().Key;
}
}
return medianSum;
}
示例2: getRateForDate
public decimal getRateForDate(string date, string currency)
{
decimal rate = 0;
string downloadYear = date.Substring(0, 4);
if (ratesHistory == null || year != downloadYear)
{
ratesHistory = downloadHistoryForYear(downloadYear);
}
if (ratesHistory != null && ratesHistory.Count > 0)
{
SortedDictionary<string, RateModel> sortedRatesHistory = new SortedDictionary<string, RateModel>(ratesHistory);
string minimumDate = sortedRatesHistory.First().Key;
if (sortedRatesHistory.ContainsKey(date))
{
rate = sortedRatesHistory[date].GetRateForCurrency(currency);
}
else
{
DateTime minimumDateTime = Convert.ToDateTime(minimumDate);
DateTime checkDate = Convert.ToDateTime(date);
while (checkDate > minimumDateTime && !sortedRatesHistory.ContainsKey(checkDate.ToString("yyyy-MM-dd")))
{
DateTime oldDate = Convert.ToDateTime(date);
checkDate = checkDate.AddDays(-1);
}
string dat = checkDate.ToString("yyyy-MM-dd");
rate = sortedRatesHistory[dat].GetRateForCurrency(currency);
}
}
return rate;
}
示例3: TestNeedGreedSorting
public void TestNeedGreedSorting()
{
var rolls = new SortedDictionary<LootRollEntry, int>();
rolls.Add(new LootRollEntry(20, LootRollType.Greed), 20);
rolls.Add(new LootRollEntry(10, LootRollType.Greed), 10);
Assert.AreEqual(10, rolls.First().Value);
}
示例4: CalculateReduction
public SortedDictionary<double, double> CalculateReduction(SortedDictionary<double, double> input, double percentage)
{
if (input.Count <= 2)
{
return input;
}
else if (percentage<= 0)
{
var first = input.First();
var last = input.Last();
return new SortedDictionary<double, double>() { {first.Key, first.Value}, {last.Key,last.Value} };
}
var m = new MathFunctions();
var temp = (from n in input select new Point(n.Key, n.Value)).ToList();
var result = temp.ToList();
var points = temp.Count;
double factor = 1.5;
double calcfactor = Math.Max(1.5, lastfactor / (factor * factor));
var euclistx = new List<double>();
for (int i = 0; i < temp.Count - 1; i++)
{
euclistx.Add(Math.Sqrt((temp[i].X - temp[i + 1].X) * (temp[i].X - temp[i + 1].X)));
}
var thresholdx = Convert.ToDouble(euclistx.Average());
var thresh = GetAveragePerpendicularDistance(temp);
var xpercentage = 1.0;
var difftotal = m.CalculateDifference(temp, new List<Point>() { temp.First(), temp.Last() });
while (xpercentage > percentage)
{
//var intermediate = m.DouglasPeuckerReduction(temp, calcfactor * thresh);
var intermediate = m.DouglasPeuckerReductionNoStack(temp, calcfactor * thresh);
calcfactor = calcfactor * factor;
lastfactor = calcfactor;
var diff = m.CalculateDifference(temp, intermediate);
xpercentage = 1 - (diff / difftotal);
if (xpercentage > percentage)
result = intermediate.ToList();
}
var resultdict = new SortedDictionary<double, double>();
foreach ( var n in result)
resultdict.Add(n.X,n.Y);
return resultdict;
}
示例5: determineLeaves
public void determineLeaves(int nodeNO, Matrix<double> theta, Matrix<double> randomWalkMX,
Vector<double> pi)
{
string[] signTraces = determineSignTraces(nodeNO, theta);
int dist = computeHammingDistance(signTraces[0], signTraces[1]);
List<int> firstPart;
List<int> secondPart;
List<int> nodeList = Enumerable.Range(0, nodeNO).ToList();
determinePotentialParts(signTraces, nodeList, out firstPart, out secondPart);
double normCutValue = determineNormCut(randomWalkMX, pi, firstPart, secondPart);
NormCutComparer normCutComparer = new NormCutComparer();
SortedDictionary<NormCutLeaf, int> sortedDict = new SortedDictionary<NormCutLeaf, int>(normCutComparer);
NormCutLeaf firstPartLeaf = determineNormCutLeafForPart(signTraces, firstPart, randomWalkMX, pi);
NormCutLeaf secondPartLeaf = determineNormCutLeafForPart(signTraces, secondPart, randomWalkMX, pi);
sortedDict.Add(firstPartLeaf, 0);
sortedDict.Add(secondPartLeaf, 0);
NormCutLeaf n = sortedDict.First().Key;
}
示例6: findSum
public long findSum(int[] m, int R)
{
List<int> desc = new List<int>();
for (int i = 0; i < m.Length; i++)
{
if (i == 0 || m[i] < desc[desc.Count - 1]) { desc.Add(m[i]); }
}
SortedDictionary<int, List<int>> resets =new SortedDictionary<int, List<int>>();
foreach (int i in desc)
{
var basis = new List<int>();
basis.Add(i);
resets.Add(i, basis);
}
int curMin = desc[desc.Count - 1];
int val = 1;
long total = 0;
for (int i = 1; i <= R; i++)
{
if (i == curMin)
{
val = 0;
List<int> basis = resets[curMin];
resets.Remove(curMin);
foreach (int b in basis)
{
List<int> other;
if (!resets.TryGetValue(curMin + b, out other))
{
other = new List<int>();
resets[curMin + b] = other;
}
other.Add(b);
}
curMin = resets.First().Key;
}
total += val;
val++;
}
return total;
}
示例7: ComputeVoronoiGraph
/// <summary>
/// Calculates a list of edges and junction vertices by using the specified points.
/// This defaults to not using any tolerance for determining if points are equal,
/// and will not use the cleanup algorithm, which breaks the HandleBoundaries
/// method in the Voronoi class.
/// </summary>
/// <param name="vertices">The original points to use during the calculation</param>
/// <returns>A VoronoiGraph structure containing the output geometries</returns>
public static VoronoiGraph ComputeVoronoiGraph(double[] vertices)
{
//BinaryPriorityQueue pq = new BinaryPriorityQueue();
SortedDictionary<VEvent, VEvent> pq = new SortedDictionary<VEvent, VEvent>();
Dictionary<VDataNode, VCircleEvent> currentCircles = new Dictionary<VDataNode, VCircleEvent>();
VoronoiGraph vg = new VoronoiGraph();
VNode rootNode = null;
for (int i = 0; i < vertices.Length / 2; i++)
{
//pq.Push(new VDataEvent(new Vector(vertex)));
VDataEvent e = new VDataEvent(new Vector2(vertices, i * 2));
if (pq.ContainsKey(e)) continue;
pq.Add(e, e);
}
while (pq.Count > 0)
{
//VEvent ve = pq.Pop() as VEvent;
VEvent ve = pq.First().Key;
pq.Remove(ve);
VDataNode[] circleCheckList = new VDataNode[] { };
if (ve is VDataEvent)
{
rootNode = VNode.ProcessDataEvent(ve as VDataEvent, rootNode, vg, ve.Y, out circleCheckList);
}
else if (ve is VCircleEvent)
{
currentCircles.Remove(((VCircleEvent)ve).NodeN);
if (!((VCircleEvent)ve).Valid)
continue;
rootNode = VNode.ProcessCircleEvent(ve as VCircleEvent, rootNode, vg, out circleCheckList);
}
else if (ve != null) throw new Exception("Got event of type " + ve.GetType() + "!");
foreach (VDataNode vd in circleCheckList)
{
if (currentCircles.ContainsKey(vd))
{
currentCircles[vd].Valid = false;
currentCircles.Remove(vd);
}
if (ve == null) continue;
VCircleEvent vce = VNode.CircleCheckDataNode(vd, ve.Y);
if (vce == null) continue;
//pq.Push(vce);
pq.Add(vce, vce);
currentCircles[vd] = vce;
}
if (!(ve is VDataEvent)) continue;
Vector2 dp = ((VDataEvent)ve).DataPoint;
foreach (VCircleEvent vce in currentCircles.Values)
{
if (MathTools.Dist(dp.X, dp.Y, vce.Center.X, vce.Center.Y) < vce.Y - vce.Center.Y && Math.Abs(MathTools.Dist(dp.X, dp.Y, vce.Center.X, vce.Center.Y) - (vce.Y - vce.Center.Y)) > 1e-10)
vce.Valid = false;
}
}
// This is where the MapWindow version should exit since it uses the HandleBoundaries
// function instead. The following code is needed for Benjamin Ditter's original process to work.
if (!DoCleanup) return vg;
VNode.CleanUpTree(rootNode);
foreach (VoronoiEdge ve in vg.Edges)
{
if (ve.Done)
continue;
if (ve.VVertexB != VVUnkown) continue;
ve.AddVertex(VVInfinite);
if (Math.Abs(ve.LeftData.Y - ve.RightData.Y) < 1e-10 && ve.LeftData.X < ve.RightData.X)
{
Vector2 t = ve.LeftData;
ve.LeftData = ve.RightData;
ve.RightData = t;
}
}
ArrayList minuteEdges = new ArrayList();
foreach (VoronoiEdge ve in vg.Edges)
{
if (ve.IsPartlyInfinite || !ve.VVertexA.Equals(ve.VVertexB)) continue;
minuteEdges.Add(ve);
// prevent rounding errors from expanding to holes
foreach (VoronoiEdge ve2 in vg.Edges)
{
if (ve2.VVertexA.Equals(ve.VVertexA))
ve2.VVertexA = ve.VVertexA;
if (ve2.VVertexB.Equals(ve.VVertexA))
ve2.VVertexB = ve.VVertexA;
}
}
//.........这里部分代码省略.........
示例8: findNearbyStars
//Find nearby Stars greedily
private HashSet<BalancingStarSystem> findNearbyStars(double maxDistance, BalancingPlayer player)
{
BalancingStarSystem start = player.SpawnStar;
//Create a list of stars in range of the player and also to prevent doubly adding stars.
HashSet<BalancingStarSystem> starsInRange = new HashSet<BalancingStarSystem>();
SortedDictionary<double,BalancingStarSystem> visitableStars = new SortedDictionary<double,BalancingStarSystem>();
start.PlayerDistance.Add(player, 0.0);
visitableStars.Add(0.0, start);
starsInRange.Add(start);
while (visitableStars.Count > 0)
{
KeyValuePair<double, BalancingStarSystem> pair = visitableStars.First();
visitableStars.Remove(pair.Key);
//Trace.WriteLine("Visiting distance: " + pair.Key);
HashSet<StarSystem> connectedStars = pair.Value.attachedStarSystem.destinations;
foreach(StarSystem star in connectedStars){
BalancingStarSystem bstar = StarCorrespondence[star];
double distance = star.directDistanceTable[start.attachedStarSystem];
//If the target system is too far ignore it.
//If the the system has already been added ignore it.
//If there is a wormhole between the two ignore this connection.
if (distance < maxDistance
&& !starsInRange.Contains(bstar)
&& !wormhole(star, pair.Value.attachedStarSystem))
{
bstar.PlayerDistance.Add(player, distance);
visitableStars.Add(distance, bstar);
starsInRange.Add(bstar);
}
}
}
return starsInRange;
}
示例9: searchPathOnMap
/// <summary>
/// Searches a path on a given map. The map data is altered in the process and a path is set on it.
/// </summary>
/// <param name="whatMap">The map to search a path on</param>
/// <returns>Whether a path could be found</returns>
public static SearchResult searchPathOnMap(WorldMap whatMap)
{
if (whatMap.goal == null || whatMap.start == null)
throw new ArgumentException("The provided map does either not have a start or a goal.", "whatMap");
SearchResult currentResult = SearchResult.None;
//Initialize open list
SortedDictionary<int, List<MapNode>> openList = new SortedDictionary<int, List<MapNode>>();
MapNode cache = whatMap.actualMap[whatMap.start.Item1][whatMap.start.Item2][whatMap.start.Item3];
cache.currentShortestPathToNode = 0;
openList.Add(cache.possibleDistanceToGoal, new List<MapNode>() { cache });
//Very simple test whether it makes sense to search the map at all
if (cache.currentStatus == MapNode.Status.isClosed)
{
currentResult |= SearchResult.MapHasAlreadyBeenSearched;
cache = whatMap.actualMap[whatMap.goal.Item1][whatMap.goal.Item2][whatMap.goal.Item3];
for (int i = 0; i < CIRCLE_TIMEOUT && cache != null && cache != whatMap.start; i++)
{
cache = cache.currentPredesessorNode;
}
if (cache != null)
{
if (cache == whatMap.start)
currentResult |= SearchResult.FoundPath;
else
throw new Exception("Map has been altered to contain a circle as a path");
}
}
else
{
//The actual searching. Take the node with the possibly least remaining distance ( estimated ) and expand it
while (openList.Any())
{
cache = openList.First().Value.First();
//remove it from the open list and possibly the entire entry list if empty
openList[cache.possibleDistanceToGoal].Remove(cache);
if (!openList[cache.possibleDistanceToGoal].Any())
openList.Remove(cache.possibleDistanceToGoal);
//Have we found the goal?
if (cache == whatMap.goal)
{
currentResult = SearchResult.FoundPath;
break;
}
cache.currentStatus |= MapNode.Status.isClosed;
expandNode(cache, openList, whatMap);
}
//Create the path information on the map data ( This is an extra list for simplicity, the main data has been altered already above )
LinkedList<BlockInfo> path = new LinkedList<BlockInfo>();
if (currentResult.HasFlag(SearchResult.FoundPath))
{
cache = whatMap.actualMap[whatMap.goal.Item1][whatMap.goal.Item2][whatMap.goal.Item3];
while (cache.currentPredesessorNode != null)
{
path.AddFirst(new BlockInfo(cache.x, cache.y, cache.z, cache.currentStatus));
cache = cache.currentPredesessorNode;
}
//Add the start aswell even though its predecessor is null ( obviously )
path.AddFirst(new BlockInfo(cache.x, cache.y, cache.z, cache.currentStatus));
}
whatMap.path = path;
}
return currentResult;
}
示例10: get_top
public SortedDictionary<String, double> get_top(int n)
{
SortedDictionary<String, double> best_so_fars = new SortedDictionary<String, double>();
double worst_score_in_best = -100.0; // assume dt small enough so nobody negative
foreach(var pair in phrases)
{
double score = pair.Value.get_importance();
String sentence = pair.Key;
if(sentence.Split().Count() <= 1) {continue;} // don't include single words.
if(best_so_fars.Count() < n)
{
if(!best_so_fars.ContainsKey(sentence)) {best_so_fars.Add(sentence, score);}
if(score < worst_score_in_best) {worst_score_in_best = score;}
}
else if(score > worst_score_in_best)
{
if(!best_so_fars.ContainsKey(sentence)) {best_so_fars.Add(sentence, score);}
best_so_fars.Remove(best_so_fars.First().Key);
}
} return best_so_fars;
}
示例11: BatchInsertAPM
public void BatchInsertAPM()
{
CloudTableClient tableClient = GenerateCloudTableClient();
TableServiceContext ctx = tableClient.GetTableServiceContext();
// Insert Entities
SortedDictionary<string, ComplexEntity> entities = new SortedDictionary<string, ComplexEntity>();
for (int i = 0; i < 100; i++)
{
ComplexEntity insertEntity = new ComplexEntity("insert test", "foo" + i);
entities.Add(insertEntity.RowKey, insertEntity);
ctx.AddObject(currentTable.Name, insertEntity);
}
DataServiceResponse response;
using (ManualResetEvent evt = new ManualResetEvent(false))
{
IAsyncResult asyncRes = null;
ctx.BeginSaveChangesWithRetries(SaveChangesOptions.Batch, (res) =>
{
asyncRes = res;
evt.Set();
}, null);
evt.WaitOne();
response = ctx.EndSaveChangesWithRetries(asyncRes);
}
Assert.AreEqual((int)HttpStatusCode.Accepted, response.BatchStatusCode);
// Retrieve Entities
List<ComplexEntity> retrievedEntities = (from ent in ctx.CreateQuery<ComplexEntity>(currentTable.Name)
where ent.PartitionKey == entities.First().Value.PartitionKey
select ent).AsTableServiceQuery(ctx).Execute().ToList();
Assert.AreEqual(entities.Count, retrievedEntities.Count);
foreach (ComplexEntity retrievedEntity in retrievedEntities)
{
ComplexEntity.AssertEquality(entities[retrievedEntity.RowKey], retrievedEntity);
entities.Remove(retrievedEntity.RowKey);
}
Assert.AreEqual(0, entities.Count);
}
示例12: FindWindowScreen
static Rectangle? FindWindowScreen(Point location)
{
SortedDictionary<float, Rectangle> distance = new SortedDictionary<float, Rectangle>();
foreach (var rect in (from screen in Screen.AllScreens
select screen.WorkingArea))
{
if (rect.Contains(location) && !distance.ContainsKey(0.0f))
return null; // title in screen
int midPointX = (rect.X + rect.Width / 2);
int midPointY = (rect.Y + rect.Height / 2);
float d = (float)Math.Sqrt((location.X - midPointX) * (location.X - midPointX) +
(location.Y - midPointY) * (location.Y - midPointY));
distance.Add(d, rect);
}
if (distance.Count > 0)
{
return distance.First().Value;
}
else
{
return null;
}
}
示例13: ResultResearch
/*private void startExtended_Click(object sender, EventArgs e)
{
ResultResearch result = new ResultResearch();
result.Name = this.jobName;
result.ModelType = typeof(HierarchicModel);
result.Delta = Double.Parse(this.deltaExtendedTxt.Text);
result.RealizationCount = (Int32)this.realizationCountNum.Value;
result.Function = this.probabilityFunctionCmb.Text;
result.GenerationParams[GenerationParam.BranchIndex] = Int16.Parse(this.branchIndexCmb.Text);
result.GenerationParams[GenerationParam.Level] = Int16.Parse(this.maxLevelCmb.Text);
result.Size = (int)Math.Pow(Int16.Parse(this.branchIndexCmb.Text), Int16.Parse(this.maxLevelCmb.Text));
Int16 maxLevel = Int16.Parse(this.maxLevelCmb.Text);
for (Int16 g = 1; g <= maxLevel; ++g)
{
result.Result.Add(g, AnalyzeExtendedHierarchic(g));
}
XMLResultStorage storage = new XMLResultStorage(Options.StorageDirectory);
storage.SaveResearch(result);
MessageBox.Show("Results are saved succesfully!");
}*/
private void startER_Click(object sender, EventArgs e)
{
ResultResearch result = new ResultResearch();
result.Name = this.jobName;
result.ModelType = typeof(ERModel);
// TODO remove hardcoded data
result.Delta = 0.00001;
result.RealizationCount = 100;
result.GenerationParams[GenerationParam.Vertices] = 65536;
SortedDictionary<double, SubGraphsInfo> pInfo =
new SortedDictionary<double, SubGraphsInfo>();
this.folderBrowserDialog1.ShowDialog();
string dirName = this.folderBrowserDialog1.SelectedPath;
DirectoryInfo parentDir = new DirectoryInfo(dirName);
foreach (FileInfo f in parentDir.GetFiles())
{
double p = Double.Parse(f.Name.Remove(f.Name.Length - 4));
SubGraphsInfo value = new SubGraphsInfo();
SortedDictionary<int, double> r = new SortedDictionary<int, double>();
using (StreamReader streamReader = new StreamReader(f.FullName, System.Text.Encoding.Default))
{
string contents;
while ((contents = streamReader.ReadLine()) != null)
{
string first = "", second = "";
int j = 0;
while (contents[j] != ' ')
{
first += contents[j];
++j;
}
second = contents.Substring(j);
r.Add(int.Parse(first), double.Parse(second));
}
}
value.avgOrder = r.First().Value;
value.avgOrderCount = r.First().Key;
if (r.Count > 1)
{
r.Remove(r.First().Key);
value.secondMax = r.First().Value;
value.secondMaxCount = r.First().Key;
}
if (r.Count > 2)
{
r.Remove(r.First().Key);
value.avgOrderRest = r.Average(x => x.Value);
}
pInfo.Add(p, value);
}
result.Result.Add(1, pInfo);
XMLResultStorage storage = new XMLResultStorage(Options.StorageDirectory);
storage.SaveResearch(result);
MessageBox.Show("Results are saved succesfully!");
}
示例14: PutAll
public IDictionary<Number640, Enum> PutAll(SortedDictionary<Number640, Data> dataMap, IPublicKey publicKey, bool putIfAbsent, bool domainProtection,
bool sendSelf)
{
if (dataMap.Count == 0)
{
return Convenient.EmptyDictionary<Number640, Enum>();
}
var min = dataMap.First().Key; // TODO check if correct
var max = dataMap.Last().Key;
var retVal = new Dictionary<Number640, Enum>();
var keysToCheck = new HashSet<Number480>();
var rangeLock = Lock(min, max);
try
{
foreach (var kvp in dataMap)
{
var key = kvp.Key;
keysToCheck.Add(key.LocationAndDomainAndContentKey);
var newData = kvp.Value;
if (!SecurityDomainCheck(key.LocationAndDomainKey, publicKey, publicKey, domainProtection))
{
retVal.Add(key, PutStatus.FailedSecurity);
continue;
}
// We need this check in case we did not use the encoder/deconder,
// which is the case if we send the message to ourself. In that
// case, the public key of the data is never set to the message
// publick key, if the publick key of the data was null.
IPublicKey dataKey;
if (sendSelf && newData.PublicKey == null)
{
dataKey = publicKey;
}
else
{
dataKey = newData.PublicKey;
}
if (!SecurityEntryCheck(key.LocationAndDomainAndContentKey, publicKey, dataKey, newData.IsProtectedEntry))
{
retVal.Add(key, PutStatus.FailedSecurity);
continue;
}
var contains = _backend.Contains(key);
if (contains)
{
if(putIfAbsent)
{
retVal.Add(key, PutStatus.FailedNotAbsent);
continue;
}
var oldData = _backend.Get(key);
if(oldData.IsDeleted)
{
retVal.Add(key, PutStatus.Deleted);
continue;
}
if(!oldData.BasedOnSet.Equals(newData.BasedOnSet))
{
retVal.Add(key, PutStatus.VersionFork);
continue;
}
}
var oldData2 = _backend.Put(key, newData);
long expiration = newData.ExpirationMillis;
// handle timeout
_backend.AddTimeout(key, expiration);
if(newData.HasPrepareFlag)
{
retVal.Add(key, PutStatus.OkPrepared);
}
else
{
if(newData.Equals(oldData2))
{
retVal.Add(key, PutStatus.OkUnchanged);
}
else
{
retVal.Add(key, PutStatus.Ok);
}
}
}
//now check for forks
foreach (var key in keysToCheck)
{
var minVersion = new Number640(key, Number160.Zero);
var maxVersion = new Number640(key, Number160.MaxValue);
var tmp = _backend.SubMap(minVersion, maxVersion, -1, true);
var heads = GetLatestInternal(tmp);
if(heads.Count > 1)
{
foreach (var fork in heads.Keys)
{
if(retVal.ContainsKey(fork))
{
//.........这里部分代码省略.........
示例15: Main
static void Main(string[] args)
{
int nc = int.Parse(Console.ReadLine());
for (int i = 0; i < nc; i++)
{
string [] kn = Console.ReadLine().Split(' ');
string [] abcr = Console.ReadLine().Split(' ');
int n = int.Parse(kn[0]);
int k = int.Parse(kn[1]);
int a = int.Parse(abcr[0]);
int b = int.Parse(abcr[1]);
int c = int.Parse(abcr[2]);
int r = int.Parse(abcr[3]);
List<int> v = new List<int>();
SortedDictionary<int, Counter> sd = new SortedDictionary<int, Counter>();
long m = a;
v.Add(a);
sd.Add(a, new Counter());
for (int j = 1; j < k; j++)
{
m = (b * m + c) % r;
v.Add((int)m);
Counter cv;
if (sd.TryGetValue((int)m, out cv))
{
cv.Inc();
}
else
{
sd.Add((int)m, new Counter());
}
}
CleanUp(ref sd, k + 1);
HashSet<int> active = new HashSet<int>(sd.Keys);
int l = 0;
int p = 0;
int next_p = int.MaxValue;
while (true)
{
if (active.Contains(p))
p = FindNext(sd);
next_p = int.MaxValue;
if (p == k && (sd.First().Key == 0) && (sd.Last().Key == k-1))
{
// We have all values in [0..k-1], there is no need to search for other values
int f;
long ma = ((long)(n-k)) % ((long)k * (long)(k+1));
for (int o = 0; o < ma; o++, l++)
{
l = l % v.Count;
f = v[l];
v[l] = p;
p = f;
}
if (l > 0)
p = v[l - 1];
else
p = v[v.Count - 1];
break;
}
if (l < v.Count)
{
l++;
}
else
{
l = 1;
}
Counter cv;
if (sd.TryGetValue(v[l - 1], out cv))
{
cv.Dec();
if (cv.Value == 0)
{
if (p > v[l - 1])
{
next_p = v[l - 1];
}
active.Remove(v[l - 1]);
sd.Remove(v[l - 1]);
}
}
//if (sd.TryGetValue((int)p, out cv))
//.........这里部分代码省略.........