473,804 Members | 2,989 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

List of integers & L.I.S.

Given a list of N arbitrarily permutated integers from set {1..N}.
Need to find the ordering numbers of each integer in the LONGEST
increasing sequence to which this number belongs. Sample:

List:
[4, 5, 6, 1, 2, 7, 3]

Corresponding ordering numbers:
[1, 2, 3, 1, 2, 4, 3]

Details:
e.g. number 7 belongs to increasing sequence 1, 2, 7;
but this sequence is not the LONGEST sequence for "7".
The longest sequence for the 7 is 4, 5, 6, 7.
So, the 7's ordering number in this sequence is 4.

The salt of the thing is to do this with an O(n*log(n))
algorithm!
The straightforward O(n^2) algorithm is toooo slooow.

Any ideas?

Sep 7 '05
39 3121
n00m wrote:
Oh!
Seems you misunderstand me!
See how the last block in your code should look:

for tc in range(10):
_ = stdin.readline( )
sequence = [int(ch) for ch in stdin.readline( ).split()]
supers = supernumbers(se quence)
print len(supers)
for i in supers:
print i,


Ah, I misunderstood the input. I thought they'd run it once for
each of their test cases. Handling exactly ten inputs sucks, so
how about:

while True:
if not stdin.readline( ).strip():
break
sequence = [int(ch) for ch in stdin.readline( ).split()]
supers = supernumbers(se quence)
print len(supers)
for i in supers:
print i,
print
--
--Bryan
Sep 9 '05 #21
It also timed out:(

241056 2005-09-09 20:11:19 ZZZ time limit exceeded - 7064 PYTH

Btw, have a look at this nicest problem:

http://spoj.sphere.pl/problems/COINS/

My py solution takes #64 place among its best solutions:

http://spoj.sphere.pl/ranks/COINS/start=60

Sep 9 '05 #22
PS:
ALL problems in problems.PDF file (weekly updated):

http://spoj.sphere.pl/problems.pdf

The friendliest online contester I've ever seen! JUST A NON-SUCH.

Sep 9 '05 #23
n00m wrote:
It also timed out:(
Could be. Yet you did write:
It's incredibly fast!

I never intended to submit this program for competition. The
contest ranks in speed order, and there is no way Python can
compete with truly-compiled languages on such low-level code.
I'd bet money that the algorithm I used (coded in C) can run
with the winners. I also think I'd wager that the Python version
outright trumps them on code size.
My first version bombed for the zero-length sequence. That was a
mistake, sorry, but it may not be one of their test-cases. I
wonder how many of the accepted entries would perform properly.
--
--Bryan
Sep 9 '05 #24

Bryan Olson wrote:
Could be. Yet you did write:
> It's incredibly fast!
I just was obliged to exclaim "It's incredibly fast!"
because I THOUGHT your first version handled ALL TEN
testcases from the input. But the code read from the
*20-lines* input *ONLY 2* its first lines.

Usually they place heavy data testcase(s) at the end
of the (whole) input. Like this:

3
2 3 1
7
4 5 6 1 2 7 3
....
....
....
100000
456 2 6789 ... ... ... ... ... 55444 1 ... 234

Surely producing an answer for list [2, 3, 1] will
be "incredibly fast" for ANY language and for ANY
algorithm.
My first version bombed for the zero-length sequence. That was a
mistake, sorry, but it may not be one of their test-cases. In my turn I can bet there's not an empty sequence testcase in the
input.
I
wonder how many of the accepted entries would perform properly. Info of such kind they keep in secret (along with what the input
data are).

One more thing.
They (the e-judge's admins) are not gods and they don't warrant
that if they put 9 sec timelimit for a problem then this problem
can be "solved" in all accepted languages (e.g. in Python).
I never intended to submit this program for competition.

"Competitio n" is not quite relevant word here. It just LOOKS as
if it is a "regular" competetion. There nobody blames anybody.
Moreover, judging on my own experience, there nobody is even
interested in anybody. It's just a fun (but very useful fun).

Sep 10 '05 #25
Bryan;
My own version also timed out.
And now I can tell: it's incredibly SLOW.
Nevertheless it would be interesting to compare
speed of my code against yours. I can't do it myself
because my Python is of 2.3.4 version.

Just uncomment "your" part.
import bisect

def oops(w,a,b):
for m in w:
j=bisect.bisect _left(a,m)
a.insert(j,m)
b.insert(j,max( b[:j]+[0])+1)

def n00m(n,w):
a,b=[],[]
oops(w,a,b)
v=map(lambda x: -x, w[::-1])
c,d=[],[]
oops(v,c,d)
e=map(sum, zip(b, d[::-1]))
mx=max(e)
f=[]
for i in xrange(n):
if e[i]==mx:
f.append(i+1)
print len(f)
def one_way(seq):
n = len(seq)
dominators = [n + 1] * (n * 1)
score = [None] * n
end = 0
for (i, x) in enumerate(seq):
low, high = 0, end
while high - low > 10:
mid = (low + high) >> 1
if dominators[mid] < x:
low = mid + 1
else:
high = mid + 1
while dominators[low] < x:
low += 1
dominators[low] = x
score[i] = low
end = max(end, low + 1)
return score

def supernumbers(se q):
forscore = one_way(seq)
opposite = [len(seq) - x for x in reversed(seq)]
backscore = reversed(one_wa y(opposite))
score = map(sum, zip(forscore, backscore))
winner = max(score + [0])
return sorted([seq[i] for i in range(len(seq)) if score[i] ==
winner])

def b_olson(sequenc e):
supers = supernumbers(se quence)
print len(supers)

import random, time
n=50000
w=range(1,n+1)
random.shuffle( w)

t=time.time()
n00m(n,w)
print 'n00m:',time.ti me()-t

"""
t=time.time()
b_olson(w)
print 'b_olson:',time .time()-t
"""

Sep 10 '05 #26
[Bryan Olson, on the problem at
http://spoj.sphere.pl/problems/SUPPER/
]
I never intended to submit this program for competition. The
contest ranks in speed order, and there is no way Python can
compete with truly-compiled languages on such low-level code.
I'd bet money that the algorithm I used (coded in C) can run
with the winners. I also think I'd wager that the Python version
outright trumps them on code size.
Oh, it's not that bad <wink>. I took a stab at a Python program for
this, and it passed (3.44 seconds). It just barely made it onto the
list of "best" solutions, which I also guess is ranked by elapsed
runtime. The Java program right above it took 2.91 seconds, but ate
more than 27x as much RAM ;-)

I didn't make any effort to speed this, beyond picking a reasonable
algorithm, so maybe someone else can slash the runtime (while I
usually enjoy such silliness, I can't make time for it at present).
I'll include the code below.

Alas, without access to the input data they use, it's hard to guess
what might be important in their data. On my home box, chewing over
random 100,000-element permutations took less than a second each
(including the time to generate them); I'm pretty sure they're using
slower HW than mine (3.4 GHz P5).
My first version bombed for the zero-length sequence. That was a
mistake, sorry, but it may not be one of their test-cases. I
wonder how many of the accepted entries would perform properly.


No idea here, and didn't even think about it.

Notes: the `all` returned by crack() is a list such that all[i] is
list of all (index, value) pairs such that the longest increasing
subsequence ending with `value` is of length i+1; `value` is at index
`index` in the input permutation. The maximal LISs thus end with the
values in all[-1]. findall() iterates backwards over `all`, to
accumulate all the values that appear in _some_ maximal LIS. There's
clearly wasted work in findall() (if someone is looking for an
algorithmic point to attack). Curiously, no use is made of that
values are integers, outside of input and output; any values with a
total ordering would work fine in crack() and findall().

"""
# http://spoj.sphere.pl/problems/SUPPER/

def crack(xs):
from bisect import bisect_right as find
smallest = []
all = []
n = 0
for index, x in enumerate(xs):
i = find(smallest, x)
if i == n:
smallest.append (x)
all.append([(index, x)])
n += 1
else:
all[i].append((index, x))
if x < smallest[i]:
smallest[i] = x
return all

def findall(all):
constraints = all[-1]
allints = [pair[1] for pair in constraints]
for i in xrange(len(all) - 2, -1, -1):
survivors = []
for pair in all[i]:
index, value = pair
for index_limit, value_limit in constraints:
if index < index_limit and value < value_limit:
survivors.appen d(pair)
allints.append( value)
break
constraints = survivors
return sorted(allints)

def main():
import sys
while 1:
n = sys.stdin.readl ine()
if not n:
break
n = int(n)
perm = map(int, sys.stdin.readl ine().split())
assert n == len(perm)
supers = findall(crack(p erm))
perm = None # just to free memory
print len(supers)
print " ".join(map( str, supers))

if __name__ == "__main__":
main()
"""
Sep 11 '05 #27
Tim Peters;
INCREDIBLE~
241433 2005-09-11 04:23:40 Tim Peters accepted 3.44 7096 PYTH BRAVO!
I just wonder have I grey cells enough for to understand how your
algo works... and hopefully it's not your last solved problem on
the contester.
I'm pretty sure they're using
slower HW than mine (3.4 GHz P5).

As I mentioned before their 4 identical machines are PIII Xeon 700MHz.

PS:
each accepted solution automatically gets into "Best Solutions" list.

Sep 11 '05 #28
[Tim Peters, on the problem at
http://spoj.sphere.pl/problems/SUPPER/
]
...

[n0**@narod.ru] INCREDIBLE~
241433 2005-09-11 04:23:40 Tim Peters accepted 3.44 7096 PYTH
BRAVO!
It's different now ;-) I added the two lines

import psyco
psyco.full()

and time dropped to 2.29, while memory consumption zoomed:

2005-09-11 18:44:57 Tim Peters accepted 2.29 42512 PYTH

That surprised me: my own test cases on Windows using Python 2.4.1
enjoyed the same order of speedup, but barely increased RAM usage.
Perhaps they installed an older (or newer <0.9 wink>) version of
psyco.
I just wonder have I grey cells enough for to understand how your
algo works...
You do! Work out some small examples by hand, and it will become
clear; be sure to read the comments before the code, because they
explain it.
and hopefully it's not your last solved problem on the contester.
I have to stop now, else I wouldn't do anything else <0.3 wink>.
...

Sep 11 '05 #29
Tim Peters wrote:
[Bryan Olson, on the problem at
http://spoj.sphere.pl/problems/SUPPER/
]
I never intended to submit this program for competition. The
contest ranks in speed order, and there is no way Python can
compete with truly-compiled languages on such low-level code.
I'd bet money that the algorithm I used (coded in C) can run
with the winners. I also think I'd wager that the Python version
outright trumps them on code size.
Oh, it's not that bad <wink>. I took a stab at a Python program for
this, and it passed (3.44 seconds).

[...] I didn't make any effort to speed this, beyond picking a reasonable
algorithm, so maybe someone else can slash the runtime


Hmmm ... I used the Theta(n lg n) algorithm ... how the heck...
Aha! The 'bisect' module changed since last I looked. It still
has the Python implementation, but then the last few lines say:

# Overwrite above definitions with a fast C implementation
try:
from _bisect import bisect_right, bisect_left, insort_left,
insort_right, insort, bisect
except ImportError:
pass

Binary-search is the inner-loop in this algorithm. I wrote my
own binary-search, so I was executing Theta(n lg n) Python
statements. Tim's use of bisect means that his inner-loop is
in C, so he does Theta(n) Python statements and Theta(n lg n) C
statement.

The key to fast Python: use a good algorithm, and keep the inner
loop in C.
--
--Bryan
Sep 11 '05 #30

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
9148
by: dam_fool_2003 | last post by:
Hai, I thank those who helped me to create a single linked list with int type. Now I wanted to try out for a void* type. Below is the code: #include<stdlib.h> #include<stdio.h> #include<string.h> #include<stddef.h> struct node
16
3395
by: aruna | last post by:
Given a set of integers, how to write a program in C to sort these set of integers using C, given the following conditions a. Do not use arrays b. Do not use any comparison function like if/then or switch-case c. you can use pointers only d. you cannot use any of the loops either.
7
12724
by: Girish Sahani | last post by:
Hi, Please check out the following loop,here indexList1 and indexList2 are a list of numbers. for index1 in indexList1: for index2 in indexList2: if ti1 == ti2 and not index1 != indexList1.pop(): index1+=1 index2+=1 continue
11
18560
by: Steve | last post by:
I'm trying to create a list range of floats and running into problems. I've been trying something like: a = 0.0 b = 10.0 flts = range(a, b) fltlst.append(flts)
6
4021
by: Amit Bhatia | last post by:
Hi, I am not sure if this belongs to this group. Anyway, my question is as follows: I have a list (STL list) whose elements are pairs of integers (STL pairs, say objects of class T). When I create a new object of class T, I would like to check if this object already exists in the list: meaning one having same integers. This can be done in linear time in a list, and probably faster if I use STL Set instead of list. I am wondering however if...
3
2672
by: maruf.syfullah | last post by:
Consider the following Class definitions: class AClass { int ai1; int ai2; public: CClass* c; AClass(){}
6
1884
by: python101 | last post by:
I have a list of integers s= to be converted to s= I tried s= for i in s: str(a) '2'
10
5030
by: arnuld | last post by:
It is quite an ugly hack but it is all I am able to come up with for now :-( and it does the requires work. I want to improve the program, I know you people have much better ideas ;-) /* C++ Primer - 4/e * * exercise 9.20 * STATEMENT: * Write a program to to compare whether a vector<intcontains the
2
3278
by: antar2 | last post by:
Hello, I am a beginner in python. following program prints the second element in list of lists 4 for the first elements in list 4 that are common with the elements in list 5 list4 = ,,] list5 =
0
9704
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10562
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10319
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10303
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10070
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9132
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7608
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6845
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5508
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.