I have a good idea on how this structure works and how to update it, however when it comes to work with Lazy Propagation I don't know what to do, as many many many problems requires this to pass in competitions I want to know how to make it work.
I am trying this problem on spoj: http://www.spoj.com/problems/CDC12_H/
If somebody can explain me how the lazy propagation can be adapted to this situation I will take that and work on the idea, I really don't want to post my code because the idea for me is to make this work by myself but with a little help.
I hope someone comes with the solution to my problem.
This is my snippet of segment tree implementation with lazy propagation.
Hope this will help you.
#define int long long
#define MAX 100005*3
int stree[MAX],lazy[MAX];
void update(int cur,int cur_lft,int cur_rgt,int st,int en,int val)
{
if(cur_lft>en || cur_rgt<st) return ;
if(cur_lft>=st && cur_rgt<=en)
{
stree[cur]+=val*(cur_rgt-cur_lft+1);
lazy[cur]+=val;
return;
}
int l=cur<<1,r=(cur<<1)+1,mid=(cur_lft+cur_rgt)>>1;
update(l,cur_lft,mid,st,en,val);
update(r,mid+1,cur_rgt,st,en,val);
stree[cur]=stree[l]+stree[r]+lazy[cur]*(cur_rgt-cur_lft+1);
}
int query(int cur,int cur_lft,int cur_rgt,int st,int en,int lzy)
{
if(cur_lft>en || cur_rgt<st) return 0;
if(cur_lft>=st && cur_rgt<=en) return stree[cur]+lzy*(cur_rgt-cur_lft+1);
int l=cur<<1,r=(cur<<1)+1,mid=(cur_lft+cur_rgt)>>1;
int left_tree=query(l,cur_lft,mid,st,en,lzy+lazy[cur]);
int right_tree=query(r,mid+1,cur_rgt,st,en,lzy+lazy[cur]);
return left_tree+right_tree;
}
Edit
To update and query into segment tree we can call following functions:
query(1,0,n-1,lower_range,upper_range,0));
update(1,0,n-1,lower_range,upper_range,v);
Related
I have a simple question. Is it possible to write structures of arrays like this with Alea.Gpu?
public struct SVDFactorsStructGpu
{
public deviceptr<float> ItemsBiases;
public deviceptr<float> UsersBiases;
public deviceptr<float> ItemsFeatures;
public deviceptr<float> UsersFeatures;
}
[...]
SVDFactorsStructGpu factors = new SVDFactorsStructGpu();
factors.ItemsBiases = gpuItemsBiases.Ptr;
factors.UsersBiases = gpuUsersBiases.Ptr;
factors.ItemsFeatures = gpuItemsFeatures.Ptr;
factors.UsersFeatures = gpuUsersFeatures.Ptr;
[...]
And pass them somehow like this to a kernel:
public void TrainEpochKernel(SVDParamsStructGpu svdParams,
deviceptr<float> ratings,
deviceptr<int> ratingsItemsIds,
deviceptr<int> userProfilesIds,
deviceptr<int> ratingsStartIdxs,
deviceptr<int> ratingsCounts,
deviceptr<float> userProfilesSSE,
SVDFactorsStructGpu factors)
{
int startUserProfileIdx = blockIdx.x * (blockDim.x * svdParams.StridePerThread) + threadIdx.x * svdParams.StridePerThread;
[...]
pred = svdParams.GlobalMean;
pred += factors.ItemsBiases[i];
pred += factors.UsersBiases[u];
[...]
This works without a structure but yields an illegal address when encapsulated.
Thanks in advance
[edit #1] It seems that the Ptr copy is in cause here, as if I try to pass them from the structure directly in the kernel signature the error is the same.
[edit #2] Maybe it is a very obvious question, I tried to pass the DeviceMemory<> directly but was unable to set values. I am going to keep the "one parameter for one array version" as it is not critical and got a very efficient algorithm overall. Was just curious to know more about Alea.Gpu C#.
Cf, comment above. Everything worked fine with the arrays. :)
I've been tasked to write a basic guessing game, which I have done, but part of the task is confusing me. We've been asked to create a warning when a user inputs the same guess too many times. I've tried several ways to take the previous user guess and compare them with the current one but none seem to work. Can anyone help me with this? My Google skills seem to have failed me.
Mostly I've tried this:
void guessWarning(int confirmedGuess){
int prevGuess = currentGuess;
int currentGuess = confirmedGuess;
if(prevGuess == currentGuess){
text("Same guess, try again",350,350)
}
}
There are multiple ways to tackle this.
One option would be keep track of the previous attempts in a dynamic array (see ArrayList). Here a bit of code to illustrate the concept:
//create a new list of integers
ArrayList<Integer> guesses = new ArrayList<Integer>();
//in your check function, test if the new value already exists
if(guesses.contains(NEW_GUESS_HERE)){
println("you've already tried this number");
}else{//otherwise add the current guess to keep track of for next time
guesses.add(NEW_GUESS_HERE);
}
Another option is using a HashMap. This is an associative array as opposed to an index based array. This method is more efficient and you can also keep track of how many attempts there were for each value. Be sure to read more on HashMaps: it will help you on the long run and potentially impress your tutors on the short run.
Here's a basic sketch to illustrate the idea:
//create a new hashmap of integers (key = guess, value = number of times tried)
HashMap<Integer,Integer> guesses = new HashMap<Integer,Integer>();
int answer = '=';
void setup(){}
void draw(){}
void keyPressed(){
guess(keyCode);
println(keyCode);
}
void guess(int newValue){
if(newValue == answer){
println("you guessed it!");
}else{
//check if the value was already recorded
try{
//if there was a value with this key, it's been tried before
int numberOfTries = guesses.get(newValue);
println("you've tried this value",numberOfTries,"times");
//increment the number of times this has beeen attempted
guesses.put(newValue,numberOfTries+1);
}catch(NullPointerException e){
println("it's the first time you try this number, but you haven't guessed it yet");
guesses.put(newValue,1);
}
}
}
A similar option, but a bit more hacky would be using a JSONObject.
The concept is similar: an associative array (albeit the key is a string, instead of an int), but you'd need to convert the guessed number to a string to index it first:
JSONObject guesses = new JSONObject();
int answer = '=';
void setup(){}
void draw(){}
void keyPressed(){
guess(keyCode);
println(keyCode);
}
void guess(int newValue){
if(newValue == answer){
println("you guessed it!");
}else{
//hacky int to string
String newValueStr = newValue+"";
//check if the value was already recorded
if(guesses.hasKey(newValueStr)){
//if there was a value with this key, it's been tried before
int numberOfTries = guesses.getInt(newValueStr);
println("you've tried this value",numberOfTries,"times");
//increment the number of times this has beeen attempted
guesses.setInt(newValueStr,numberOfTries+1);
}else{
println("it's the first time you try this number, but you haven't guessed it yet");
guesses.setInt(newValueStr,1);
}
}
}
One nice thing is that you could save the guesses to disk, then load it so the program could recall previous guesses even if the it was restarted.
I'll leave you the fun exercise of attempting to load the data when the sketch starts and saving the data when the sketch exists.
Context
Assessment piece for a data structures and algorithms course, an exercise in using an AVL tree and hash table to parse input to create a dictionary file and then use that file to perform cursory spell checking.
N.B.: I am not asking for help in solving this problem that's not what I'm having difficulty with. I am asking for help understanding an aspect of C++ function object passing/usage that is causing me considerable frustration. This aspect of C++ is not part of the assessment, there are no marks attached to it, I simply have a personal issue submitting code I dislike the design of.
Problem
Passing a functor to a recursive function results in compiler error, "attempt to use a deleted function." I thought this was an issue with passing the functor by value, so I changed the parameter to pass by reference which yields a, "no matching member function for call to <public member function of AVL tree that kicks off the recursion>," in which case I don't know how to alter the function declaration so it does match. I have also tried making the parameter: const UnaryFunction& action (a constant function-object reference), but this yields the compiler error, "no matching function for call to object of type 'const std::__1::__mem_fn<void (DictGen::*)(std::__1::basic_string<char> &)>'," in which case I can't understand why it wouldn't be matching to the DictGen::output signature.
Code
Relevant parts of AVL tree class:
template <class T>
struct AVLNode
{ // simple data carrier node for AVL tree
AVLNode<T>* lChild;
AVLNode<T>* rChild;
AVLBalance balFac;
T data;
};
template <class T>
class AVLTree<T>
{
...
AVLNode<T>* root;
template <class UnaryFunction>
void inorderAction( AVLNode<T>* node, UnaryFunction action )
{
if ( node != NULL )
{
inorderAction( node->lChild, action );
action( node->data ); // << problem line
inorderAction( node->rChild, action );
}
}
public:
template <class UnaryFunction>
void inorder( UnaryFunction action )
{
inorderAction( root, action );
}
}
Relevant parts of DictGen class:
class DictGen
{
...
FILE* outStream;
AVLTree<std::string> dict;
void output( std::string& word )
{
fprintf( outstream, "%s\n", word.c_str() );
}
public:
goGoGadgetDictionaryGenerator()
{
...
dict.inorder( std::mem_fn( &DictGen::output ) ); // << also problem line
}
}
Interpretation/Translation
AVL tree class has a flexible inorder traversal that allows me to action the node however I want with the given UnaryFunction action. A DictGen object is initialised with a FILE* so DictGen instances may output to different files, hence the need to pass a member function object in the dict.inorder( ... ) call.
Efforts/research so far
My initial solution was to follow the functions as parameters example given in our textbook which involved using C function pointers and polluting global space. Although this worked I was unsatisfied with this design; I wished to bundle this behaviour in a DictGen class.
My after consulting both my lecturer and lab tutor they suggested using C++ functors but weren't able to help with implementation as neither had used functors in a while.
I forged ahead finding very handy material on SO (helping me reference a member function), several functor tutorials via Google and an excellent PDF from a Stanford course regarding functor implementation and usage. However, while all these resources have carried me this far, none have been able to shed any light on my current predicament. I was really hoping making the parameter a const UnaryFunction& would solve it but can't understand why the signature doesn't match.
I have also tried using an inline lambda but require the object context to access outStream.
I have spent the last four days ploughing away at this issue and the only remaining lead I have is an SO post that casually remarked that the C++ spec contains information about the implicit deletion of function objects but I haven't been able to make any further progress. If there is an SO post that solves my issue, I haven't been able to find it.
Questions
Does the recursion really have anything to do with this issue?
Is there some novice aspect of functor passing/usage I'm not grasping?
What is causing the function to be deleted?
What am I missing about getting the function signatures to match when it appears that function deletion isn't the issue?
This is my very first SO post, I have done my best to keep the question-asking suggestions in mind. I welcome any constructive criticism to help me improve this post so that I can it can both solve my issue and serve as a future resource for similar issues.
You need to have an instance of DictGen bound to the member function:
// ...
void gen()
{
dict.inorder(
std::bind( std::mem_fn( &DictGen::output ),
this, std::placeholders::_1) );
}
// ...
You are coding in C++11. While there are uses for std::mem_fn and std::bind, they are a very awkward way to generate these kind of functors.
void gen()
{
dict.inorder(
[this]( std::string& word ) { this->output(word); }
);
}
while the lambda syntax might be somewhat new to you, this is far less backwards than the std::bind( std::mem_fn( &T::method ), this, std::placeholders::_1)
The basic syntax of a lambda is:
[capture-list]( arguments )->return value { code }
where capture-list is [=] (auto-capture by value) or [&] (auto-capture by reference) or [var1, var2] (capture var1 and var2 by value) or [&var1, &var2] (capture var1 and var2 by reference) or a mixture of same. (C++1y adds new syntax, like [x = std::move(y)])
(arguments) are just a usual function argument bit. It is actually optional, but required if you want a return value.
-> return value is optional for single-statement lambdas, or lambdas that return void. (In C++1y, it is optional even with multiple returns)
Then the code.
You must print a simply linked list backwards:
Without recursion
With constant extra memory
In linear time
Leaving the list intact
Added Later Two passes at most
Invert the list, print it forwards, invert again. Each step can be done without violating restrictions except the last one.
EDIT: As cube notes in the comments the second and the third stages can be combined into one pass. This gives two passes – first reverse, then print while reversing again.
Building on sharptooth's reply, you can combine the printing and second inversion in the same pass.
Edit: The "list is left intact" from a single-threaded view because the post-condition equals the pre-condition.
Edit 2: Not sure how I got the answer, but I'll take it since I've hit the rep cap for the day. I gave sharptooth a +1 too.
Here's a C# implementation that holds for all the current rules. It mutates the list during the execution, but the list is restored before returning.
using System;
using System.Diagnostics;
namespace SO1135917.Classes
{
public class ReverseListPrinter
{
public static void Execute(Node firstNode, Action<Node> action)
{
Reverse(Reverse(firstNode, null), action);
}
private static Node Reverse(Node firstNode, Action<Node> action)
{
Node node = firstNode;
Debug.Assert(node != null);
Node nextNode = node.Next;
node.Next = null;
while (node != null)
{
if (action != null)
action(node);
if (nextNode == null)
break;
Node nextNode2 = nextNode.Next;
nextNode.Next = node;
node = nextNode;
nextNode = nextNode2;
}
return node;
}
}
}
There is one problem, however, and that is that the state of the list is undefined if an exception should occur in the above methods. Probably not impossible to handle though.
A subversion repository of the above code, with unit tests, for Visual Studio 2008 is available here, username and password is both 'guest' without the quotes.
You can first check the length of the list. Then create a print-buffer, which you fill in backwards as you traverse the list once again for the information.
Or
You can create another linked list where you add all the printing data in the front when you traverse the first list, and then print the second list from front to back.
Either way makes only two passes at most. The first idea could be done in one pass if you have a header struct that keeps track of the amount of elements in the list.
Edit: I just realised that these ideas does not use constant memory.
The only way to do this sensibly seems to be Sharptooths reply, but that requires three passes.
a function like the following might solver your issue:
void invert_print(PtNo l){
PtNo ptaux = l;
PtNo last;
PtNo before;
while(ptaux != NULL){
last = ptaux;
ptaux = ptaux->next;
}
while(ptaux != last){
printf("%s\n", last->info.title);
ptaux = l;
before = last;
while(ptaux != before){
last = ptaux;
ptaux = ptaux->next;
}
}
}
you will need a structure like the following:
typedef struct InfoNo{
char title20];
}InfoNo;
typedef struct aPtNo{
struct InfoNo info;
struct aPtNo* nextx;
}*PtNo;
Objective-C Link class with reverse method:
Link.h
#import <Foundation/Foundation.h>
#interface Link : NSObject
#property(nonatomic) int value;
#property(nonatomic) Link *next;
- (Link*)reversedList;
#end
Link.m
#import "Link.h"
#implementation Link
- (Link*)reversedList {
Link* head;
Link *link = self;
while (link) {
// save reference to next link
Link *next = link.next;
// "insert" link at the head of the list
link.next = head;
head = link;
// continue processing the rest of the list
link = next;
}
return head;
}
#end
I am writing a utility that reflects on two object graphs and returns a value to indicate whether the graphs are identical or not. It got me thinking, is there a generally accepted pattern for writing a recursion algorithm that returns a value from some where in the recursion?
My solution would probably use a ref parameter and look something like this pseudo code:
public static bool IsChanged(T current, T previous)
{
bool isChanged = false;
CheckChanged(current, previous, ref isChanged);
return isChanged ;
}
private static void CheckChanged(T current, T previous, ref isChanged)
{
//perform recursion
if (graphIsChanged)
isChanged = true;
else
CheckChanged(current, previous, ref isChanged);
}
Is there a better / cleaner / more efficient way? Is there a general pattern for such a function?
I don't see any benefits of your version when compared to this highly trivial version:
public static bool IsChanged(T current, T previous)
{
//perform recursion
if (graphIsChanged)
return true;
else
return IsChanged(current, previous);
}
As an added benefit, some compilers are able to use tail call optimization to turn this version into a simple loop, which is more effective.
Tail recursion isn't just more effective, it keeps you from blowing out the stack on deep recursion:
http://en.wikipedia.org/wiki/Tail_recursion
That is to say, it prevents "Stack Overflow" :)
http://en.wikipedia.org/wiki/Stack_overflow
I've always been a fan of having an actual return value from a recursive function, not just passing in a reference to a variable. I[m not really sure what you're trying to do in your sample, but why not just return a bool from CheckChanged?