OmaeWaMouShenDeiru's blog

By OmaeWaMouShenDeiru, history, 10 years ago, In English

Hello,

As I was trying to solve ZigZag problem on topcoder the weirdest thing happend.

#include <bits/stdc++.h>
using namespace std;
class ZigZag {
public:
	int longestZigZag(vector<int> arr) {
		int dp[55], state[55];
		memset(dp, 1, sizeof dp);
		cout << dp[0] << endl;
		memset(state, 0, sizeof state);
		for (int i = 0; i < arr.size(); ++i) {
			for (int j = 0; j < i; ++j) {
				if ((j == 0 || (arr[i] - arr[j] < 0 && state[j] > 0)
						|| (arr[i] - arr[j] > 0 && state[j] < 0))
						&& dp[j] + 1 > dp[i])
					dp[i] = dp[j] + 1, state[i] = arr[i] - arr[j];
			}
		}
		return dp[arr.size() - 1];
	}
};

as I ran the given code, the cout statement gives 16843009.

I removed it and initialized every element int the first loop and it worked.

| Write comment?
»
10 years ago, # |
Rev. 2   Vote: I like it +3 Vote: I do not like it

memset fills every byte by the value you tell him to
00000001000000010000000100000001 = 16843009

»
10 years ago, # |
  Vote: I like it +12 Vote: I do not like it

It's not a bug. You fill the array with 0x01 bytes, so each element contains 0x01010101, that is 16843009.

»
10 years ago, # |
  Vote: I like it +2 Vote: I do not like it

It's a regular question why would some users down vote this -_-

  • »
    »
    10 years ago, # ^ |
    Rev. 5   Vote: I like it +3 Vote: I do not like it

    Because this is a question you can quickly answer yourself via a quick google.
    See memset — C++ Reference
    On top of that, It's NOT a bug — this probably explains all the downvotes.

    In the Parameter section, the page stated:
    " value
    Value to be set.
    The value is passed as an int, but the function fills the block of memory using the unsigned char conversion of this value. "