2012年9月13日 星期四

uva 556 - Amazing



  Amazing 

One of the apparently intelligent tricks that enthousiastic psychologists persuade mice to perform is solving a maze. There is still some controversy as to the exact strategies employed by the mice when engaged in such a task, but it has been claimed that the animal keepers eavesdropping on conversations between the mice have heard them say things like "I have finally got Dr. Schmidt trained. Everytime I get through the maze he gives me food".


Thus when autonomous robots were first being built, it was decided that solving such mazes would be a good test of the 'intelligence' built into such machines by their designers. However, to their chagrin, the first contest was won by a robot that placed a sensor on the right-hand wall of the maze and sped through the maze maintaining contact with the right-hand wall at all times. This led to a change in the design of mazes, and also to the interest in the behaviour of such robots. To test this behaviour the mazes were modified to become closed boxes with internal walls. The robot was placed in the south west corner and set of pointing east. The robot then moved through the maze, keeping a wall on its right at all times. If it can not proceed, it will turn left until it can proceed. All turns are exact right angles. The robot stops when it returns to the starting square. The mazes were always set up so that the robot could move to at least one other square before returning. The researchers then determined how many squares were not visited and how many were visited one, twice, thrice and four times. A square is visited if a robot moves into and out of it. Thus for the following maze, the values (in order) are: 2, 3, 5, 1, 0.

Write a program to simulate the behaviour of such a robot and collect the desired values.

Input 

Input will consist of a series of maze descriptions. Each maze description will start with a line containing the size of the maze (b and w), This will be followed by b lines, each consisting of w characters, either '0' or '1'. Ones represent closed squares, zeroes represent open squares. Since the maze is enclosed, the outer wall is not specified. The file will be terminated by a line containing two zeroes.

Output 

Output will consist of a series of lines, one for each maze. Each line will consist of 5 integer values representing the desired values, each value right justified in a field of width 3.

Sample Input 

3 5
01010
01010
00000
0 0

Sample Output 

  2  3  5  1  0



Miguel A. Revilla
1998-03-10

simulation

#include<stdio.h>
#include<cstring>
#include<cstdlib>
#include<vector>
#include<iostream>
#define REP(i, b, n) for (int i = b; i < n; i++)
#define rep(i, n) REP(i, 0, n)
#define DBG 0
using namespace std;

int N,M,D;
int dir[4][2],ndir[4],rside[4][2];
char **vc;
void init(){
    dir[0][0]=1,dir[1][1]=1,dir[2][0]=-1,dir[3][1]=-1;
    rside[0][1]=-1,rside[1][0]=1,rside[2][1]=1,rside[3][0]=-1;
    rep(i,4)ndir[i]=(i+1)%4;
}
bool isValid(int a,int b){return a>=0&&a<N&&b>=0&&b<M;}
void next(int &r,int &c){
    //if(DBG)printf("r c %d %d\n",r,c);
    int x=r+dir[D][0],y=c+dir[D][1];
    //if(DBG)printf("x y %d %d\n",x,y);
    if(isValid(x,y))
        if(vc[x][y]=='0'){
            r=x,c=y;
            if(isValid(r+rside[D][0],c+rside[D][1])&&
                vc[r+rside[D][0]][c+rside[D][1]]=='0'){
                D=(D-1)>=0?D-1:3;      //maintain against the wall
            }
        }
        else D=ndir[D],next(r,c);  //block
    else D=ndir[D],next(r,c);      //outside
}
void ans(){
    D=1;
    int steps[N][M];
    int cnt[5];
    memset(steps,0,sizeof(steps));
    memset(cnt,0,sizeof(cnt));
    int sr=N-1,sc=0,cr=N-1,cc=0;
    steps[cr][cc]=1;
    while(1){
        if(DBG)printf("cur %d %d\n",cr,cc);
        next(cr,cc);
        if(cr==N-1&&cc==0)break;else steps[cr][cc]++;
    }
    rep(i,N)rep(j,M)if(steps[i][j]<5&&vc[i][j]=='0')cnt[steps[i][j]]++;
    rep(i,5)printf("%3d",cnt[i]);
    printf("\n");
}
int main(){
    int a;
    init();
    while(scanf("%d%d",&N,&M)==2){
        if(N==0&&M==0)break;
        vc=(char **)malloc(N*sizeof(char *));
        rep(i,N)vc[i]=(char *)malloc(M+1);
        rep(i,N)scanf("%s",vc[i]);
        ans();
    }
}

2012年9月10日 星期一

uva 305 - Joseph



 Joseph 

The Joseph's problem is notoriously known. For those who are not familiar with the original problem: from among npeople, numbered 1, 2, ..., n, standing in circle every mth is going to be executed and only the life of the last remaining person will be saved. Joseph was smart enough to choose the position of the last remaining person, thus saving his life to give us the message about the incident. For example when n = 6 and m = 5 then the people will be executed in the order 5, 4, 6, 2, 3 and 1 will be saved.

Suppose that there are k good guys and k bad guys. In the circle the first k are good guys and the last k bad guys. You have to determine such minimal m that all the bad guys will be executed before the first good guy.

Input

The input file consists of separate lines containing k. The last line in the input file contains 0. You can suppose that 0 < k < 14.

Output

The output file will consist of separate lines containing m corresponding to k in the input file.

Sample Input


3
4
0

Sample Output


5
30

simulation, linked list

#include<stdio.h>
#define REP(i, b, n) for (int i = b; i < n; i++)
#define rep(i, n) REP(i, 0, n)
#define DBG 1
using namespace std;

int K;
int dp[14],next[28];
void ans(){
int left,m,i,tmp,pn,np,pre;
bool fail;
i=2*K,m=K;
//if(DBG)printf("N %d\n",i);
while(1){
fail=0,m++,left=i;
rep(j,i-1)next[j]=j+1;
next[i-1]=0;
//if(DBG)printf("%d: ",m);
np=0;
while(left>K){
pn=m%left;
if(pn==0)pn=left;
int j=np;
for(tmp=1;tmp++<pn;)pre=j,j=next[j];
//if(DBG)printf(" %d",j);
next[pre]=next[j];
if(j<K){fail=1;break;}
left--;
np=next[j];
}
if(!fail){dp[K]=m;break;}
}
}
void init(){
REP(i,1,14)K=i,ans();
}
int main(){
init();
while(scanf("%d",&K)==1){
if(K==0)break;
printf("%d\n",dp[K]);
}
}

2012年9月7日 星期五

uva 533 - Equation Solver



  Equation Solver 

Write a program that can solve linear equations with one variable.

Input Specification 

The input file will contain a number of equations, each one on a separate line. All equations are strings of less than 100 characters which strictly adhere to the following grammar (given in EBNF):
    Equation   := Expression '=' Expression
    Expression := Term { ('+' | '-') Term }
    Term       := Factor { '*' Factor }
    Factor     := Number | 'x' | '(' Expression ')'
    Number     := Digit | Digit Number
    Digit      := '0' | '1' | ... | '9'
Although the grammar would allow to construct non-linear equations like ``x*x=25", we guarantee that all equations occuring in the input file will be linear in x. We further guarantee that all sub-expressions of an equation will be linear in xtoo. That means, there won't be test cases like


x*x-x*x+x=0


which is a linear equation but contains non-linear sub-expressions (x*x).
Note that all numbers occuring in the input are non-negative integers, while the solution for x is a real number.

Output Specification 

For each test case, print a line saying ``Equation #i (where i is the number of the test case) and a line with one of the following answers:
  • If the equation has no solution, print ``No solution.".
  • If the equation has infinitely many solutions, print ``Infinitely many solutions.".
  • If the equation has exactly one solution, print ``x = solution" where solution is replaced by the appropriate real number (printed to six decimals).


Print a blank line after each test case, but the last one.

Sample Input 

x+x+x=10
4*x+2=19
3*x=3*x+1+2+3
(42-6*7)*x=2*5-10

Sample Output 

Equation #1
x = 3.333333

Equation #2
x = 4.250000

Equation #3
No solution.

Equation #4
Infinitely many solutions.

BNF calculation 先乘除後加減
#include<stdio.h>
#include<vector>
#include<string>
#include<cstring>
#include<stack>
#define REP(i, b, n) for (int i = b; i < n; i++)
#define rep(i, n) REP(i, 0, n)
#define DBG 0

using namespace std;

struct Equa{
    Equa(){cons=xfac=0;}
    Equa(int a,int b):cons(a),xfac(b){}
    Equa operator *(const Equa &b){
        Equa a;
        a.cons=cons*b.cons;
        a.xfac=cons*b.xfac+xfac*b.cons;
        return a;
    }
    Equa operator +(const Equa &b){
        Equa a;
        a.cons=cons+b.cons;
        a.xfac=b.xfac+xfac;
        return a;
    }
    Equa operator -(const Equa &b){
        Equa a;
        a.cons=cons-b.cons;
        a.xfac=xfac-b.xfac;
        return a;
    }
    int cons,xfac;
};
stack<Equa>fcs;
stack<char>ope;
int cases=1;
char chs[105];
Equa getNum(int pos,int &i){
    int c=0;
    while(isdigit(chs[pos]))c=c*10+chs[pos]-'0',pos++;
    i=pos;
    if(DBG)printf("getnum %d\n",c);
    return Equa(c,0);
}
Equa cal(char oc){
    Equa cea=fcs.top(),ea;fcs.pop();
    char co;
    if(DBG)printf("cal %c\n",oc);
    if(oc==')'){                     //clear all
        while(ope.size()&&ope.top()!='('){
            co=ope.top(),ope.pop();
            ea=fcs.top(),fcs.pop();
            if(co=='-')cea=ea-cea;
            if(co=='+')cea=ea+cea;
            if(co=='*')cea=ea*cea;
        }
        ope.pop();
    }
    if(oc=='-'||oc=='+')  {          //cal *
        while(ope.size()&&ope.top()=='*'){
            ope.pop();
            ea=fcs.top(),fcs.pop();
            //if(DBG)printf("a b (%d %d)(%d %d)\n",cea.cons,cea.xfac,ea.cons,ea.xfac);
            cea=ea*cea;
        }
    }
    if(DBG)printf("cal: (%d %d)\n",cea.cons,cea.xfac);
    return cea;
}
Equa getExp(int start,int end){
    char co;
    Equa ea,cea;
    ope.push('(');
    REP(i,start,end+1){
        if(isdigit(chs[i]))ea=getNum(i,i),fcs.push(ea);
        if(chs[i]=='x')fcs.push(Equa(0,1));
        if(chs[i]=='*'||chs[i]=='(')ope.push(chs[i]);
        if(chs[i]=='-'||chs[i]=='+')cea=cal(chs[i]),fcs.push(cea),ope.push(chs[i]);
        if(chs[i]==')')cea=cal(')'),fcs.push(cea);
        if(chs[i]=='='||chs[i]=='\0')cea=cal(')');
    }
    if(DBG){if(ope.size())printf("ope size %d\n",ope.size());
        if(fcs.size())printf("fcs size %d\n",fcs.size());
    }
    return cea;
}
void ans(){
    int len=strlen(chs);
    Equa a,b;
    rep(i,strlen(chs))if(chs[i]=='='){a=getExp(0,i),b=getExp(i+1,len);break;}
    //solve
    int xc=a.xfac-b.xfac,cc=b.cons-a.cons;
    //if(DBG)printf("xc cc %d %d\n",xc,cc);
    printf("Equation #%d\n",cases++);
    if(xc==0&&cc!=0)printf("No solution.\n");
    else if(xc==0&&cc==0)printf("Infinitely many solutions.\n");
    else printf("x = %.6f\n",(double)cc/xc);
}
int main(){
    bool ll=0;
    while(scanf("%s",chs)==1){
        if(ll)printf("\n");ll=1;
        ans();
    }
}

uva 464 - Sentence/Phrase Generator



 Sentence/Phrase Generator 

Write a program that generates English language phrases and sentences conforming to the following rules:
<sentence> ::= <trans-sentence> | <sentence> ::= <intrans-sentence>
<trans-sentence> ::= <subject> <verb-phrase> <object> <prep-phrase>
<intrans-sentence> ::= <subject> <intrans-verb-phrase> <prep-phrase>
<subject> ::= <noun-phrase>
<object> ::= <noun-phrase>
<noun-phrase> ::= <article> <modified-noun>
<modified-noun> ::= <noun> | <modifier> <noun>
<modifier> ::= <adjective> | <adverb> <adjective>
<verb-phrase> ::= <trans-verb> | <adverb> <trans-verb>
<intrans-verb-phrase> ::= <intrans-verb> | <adverb> <intrans-verb>
<prep-phrase> ::= <preposition> <noun-phrase> | <empty>
<noun> ::= man | dog | fish | computer | waves
<trans-verb> ::= struck | saw | bit | took
<intrans-verb> ::= slept | jumped | walked | swam
<article> ::= the | a
<adjective> ::= green | small | rabid | quick
<adverb> ::= nearly | suddenly | restlessly
<preposition> ::= on | over | through
<empty> ::= ""

For example, the first two lines say that to generate a sentence, one may generate a ``trans-sentence'' or an ``intrans-sentence''. A transitive sentence, according to the third rule, consists of a ``subject'', followed by a ``verb-phrase'', followed by an ``object'', followed by a ``prep-phrase''. Similarly, the next-to-last rule indicates that a ``preposition'' can be any of the three words onover, or through.

Your program should read from the input a number of requests for various kinds of phrases. Each request may be for any of the phrase names appearing on the left hand side of the above rules. It should then attempt to generate the requested phrase by applying these rules until all of the <...> have been replaced with appropriate words.

In many cases, you will face a choice of alternate rules for expanding a phrase name. In these cases, you should make a choice as follows: Suppose that this is the tex2html_wrap_inline34 such choice that you have faced since the start of execution of your program, and that you must choose one of n rules for expanding a given kind of phrase. Let the rules for that phrase be numbered from tex2html_wrap_inline38 in the order of appearance above, and then choose rule number tex2html_wrap_inline40 .

Input

The input will consist of an unspecified number of lines. Each line will contain, left-justified, a phrase name corresponding to one of the names appearing on the left-hand-side of the rules above (without the surrounding brackets).

Output

For each phrase named in the output, print a single line containing the expansion of that phrase according to the above rules. Each word in the phrase should be separated from the others by a single space.

Sample Input


sentence
noun
sentence

Sample Output


the small dog restlessly jumped through the quick dog
fish
a dog took the quick computer

BNF grammers
#include<stdio.h>
#include<vector>
#include<string>
#include<cstring>
#include<algorithm>
#include<map>
#define REP(i, b, n) for (int i = b; i < n; i++)
#define rep(i, n) REP(i, 0, n)
#define DBG 0

using namespace std;

/*{"sentence", 0
"trans-sentence", 1
"intrans-sentence", 2
"subject", 3
"object", 4
"noun-phrase", 5
"modified-noun", 6
"modifier", 7
"verb-phrase", 8
"intrans-verb-phrase", 9
"prep-phrase", 10
"noun", 11
"trans-verb", 12
"intrans-verb", 13
"article", 14
"adjective", 15
"adverb", 16
"preposition", 17
"empty" 18*/
char rname[20][25]={"sentence","trans-sentence","intrans-sentence","subject",
"object","noun-phrase","modified-noun","modifier","verb-phrase",
"intrans-verb-phrase","prep-phrase","noun","trans-verb","intrans-verb",
"article","adjective","adverb","preposition","empty"};
struct Rule{
Rule(){chs=0;}
bool type;
vector<string>nouns;
vector<int>ens[2];
int chs;
string name;
void add(int a,int b){chs=a+1,ens[a].push_back(b);}
void addN(string a){nouns.push_back(a);}
void getType(){type=nouns.size()>0?0:1;}
};
map<string,int>mp;
vector<Rule>vr;
int K=1;
bool F;
void init(){
rep(i,19){
mp[rname[i]]=i;
vr.push_back(Rule());
}
vr[11].addN("man"),vr[11].addN("dog"),vr[11].addN("fish"),vr[11].addN("computer"),vr[11].addN("waves");
vr[12].addN("struck"),vr[12].addN("saw"),vr[12].addN("bit"),vr[12].addN("took");
vr[13].addN("slept"),vr[13].addN("jumped"),vr[13].addN("walked"),vr[13].addN("swam");
vr[14].addN("the"),vr[14].addN("a");
vr[15].addN("green"),vr[15].addN("small"),vr[15].addN("rabid"),vr[15].addN("quick");
vr[16].addN("nearly"),vr[16].addN("suddenly"),vr[16].addN("restlessly");
vr[17].addN("on"),vr[17].addN("over"),vr[17].addN("through");
vr[0].add(0,1),vr[0].add(1,2), //grammers
vr[1].add(0,5),vr[1].add(0,8),vr[1].add(0,5),vr[1].add(0,10),
vr[2].add(0,5),vr[2].add(0,9),vr[2].add(0,10);
vr[3].add(0,5); //no subject
vr[4].add(0,5); //no object
vr[5].add(0,14),vr[5].add(0,6);
vr[6].add(0,11),vr[6].add(1,7),vr[6].add(1,11);
vr[7].add(0,15),vr[7].add(1,16),vr[7].add(1,15);
vr[8].add(0,12),vr[8].add(1,16),vr[8].add(1,12);
vr[9].add(0,13),vr[9].add(1,16),vr[9].add(1,13);
vr[10].add(0,17),vr[10].add(0,5),vr[10].add(1,18);
rep(i,19)vr[i].getType();
}
void gen(int rc){
int chs;
if(DBG)printf("\ngen %s\n",rname[rc]);
if(vr[rc].type==0){
chs=K%vr[rc].nouns.size();
if(!F)printf(" ");F=0;
printf("%s",vr[rc].nouns[chs].c_str());
K++;
}
else{
chs=0;
if(vr[rc].chs){
if(vr[rc].chs>1)chs=K%vr[rc].chs,K++;
rep(i,vr[rc].ens[chs].size()){
gen(vr[rc].ens[chs][i]);
}
}
}
}
void ans(char chs[]){
F=1;
int cr=mp[chs];
gen(cr);
printf("\n");
}
int main(){
char chs[30];
init();
while(scanf("%s",chs)==1){
if(DBG)printf("------------%s--------------\n",chs);
ans(chs);

}
}

2012年9月5日 星期三

uva 162 - Beggar My Neighbour


 Beggar My Neighbour 

``Beggar My Neighbour'' (sometimes known as ``Strip Jack Naked'') is a traditional card game, designed to help teach beginners something about cards and their values. A standard deck is shuffled and dealt face down to the two players, the first card to the non-dealer, the second to the dealer, and so on until each player has 26 cards. The dealer receives the last card. The non-dealer starts the game by playing the top card of her deck (the second last card dealt) face up on the table. The dealer then covers it by playing her top card face up. Play continues in this fashion until a ``face'' card (Ace, King, Queen or Jack) is played. The next player must then ``cover'' that card, by playing one card for a Jack, two for a Queen, three for a King and four for an Ace. If a face card is played at any stage during this sequence, play switches and the other player must cover that card. When this sequence has ended, the player who exposed the last face card takes the entire heap, placing it face down under her existing deck. She then starts the next round by playing one card face up as before, and play continues until one player cannot play when called upon to do so, because they have no more cards.

Write a program that will simulate playing this game. Remember that a standard deck (or pack) of cards contains 52 cards. These are divided into 4 suits--Spades ( tex2html_wrap_inline30 ), Hearts ( tex2html_wrap_inline32 ), Diamonds ( tex2html_wrap_inline34 ) and Clubs ( tex2html_wrap_inline36 ). Within each suit there are 13 cards--Ace (A), 2-9, Ten (T), Jack (J), Queen (Q) and King (K).

Input

Input will consist of a series of decks of cards. Each deck will give the cards in order as they would be dealt (that is in the example deck below, the non-dealer would start the game by playing the H2). Decks will occupy 4 lines with 13 cards on each. The designation of each card will be the suit (S, H, D, C) followed by the rank (A, 2-9, T, J, Q, K). There will be exactly one space between cards. The file will be terminated by a line consisting of a single #.

Output

Output will consist of a series of lines, one for each deck in the input. Each line will consist of the number of the winning player (1 is the dealer, 2 is the first to play) and the number of cards in the winner's hand (ignoring any on the stack), right justified in a field of width 3.

Sample input


HA H3 H4 CA SK S5 C5 S6 C4 D5 H7 HJ HQ
D4 D7 SJ DT H6 S9 CT HK C8 C9 D6 CJ C6
S8 D8 C2 S2 S3 C7 H5 DJ S4 DQ DK D9 D3
H9 DA SA CK CQ C3 HT SQ H8 S7 ST H2 D2
#

Sample output


1 44

simulation

#include<stdio.h>
#include<string>
#include<iostream>
#define REP(i, b, n) for (int i = b; i < n; i++)
#define rep(i, n) REP(i, 0, n)
#define DBG 0

using namespace std;

int fn[128];
struct Node{
    Node(){}
    Node(string a){flower=a[0];if(isdigit(a[1]))which=a[1]-'0';else which=fn[a[1]];}
    void cons(string a){flower=a[0];if(isdigit(a[1]))which=a[1]-'0';else which=fn[a[1]];}
    int which;
    char flower;
    Node *pre;
    Node *next;
};
Node *head[2],*tail[2];
int fm[14];
void init(){
    fn['A']=1,fn['J']=11,fn['Q']=12,fn['K']=13,fn['T']=10;
    fm[1]=4,fm[11]=1,fm[12]=2,fm[13]=3;
}
int getN(int term){
    int num=0;
    Node *card=head[term];
    while(card!=NULL){
        num++;
        card=card->next;
    }
    return num;
}
void run(){
    bool term=1;
    int winner,need=0,cnum=0,c[2];
    bool smode=0;
    Node *card,*ttail=NULL,*thead=NULL;
    c[0]=c[1]=26;
    while(1){
        if(head[term]==NULL){winner=!term;break;}
        card=head[term],head[term]=head[term]->next;
        c[term]--;
        if(DBG)printf("term %d play %c%d\n",term,card->flower,card->which);
        
        card->next=NULL;
        if(thead==NULL)thead=card,ttail=card;
        else ttail->next=card,ttail=card;
        cnum++;
        
        if(card->which>=11||card->which==1){
            smode=1;
            need=fm[card->which],term=!term;
            if(DBG)printf("-------------seq %d start-----------\n",need);
        }
        else if(need>0)need--;
        if(!need){      //regular or end of cover
            if(smode){
                c[!term]+=cnum;
                if(head[!term]==NULL){head[!term]=thead;tail[!term]=ttail;} //don't mess up!!
                else tail[!term]->next=thead,tail[!term]=ttail;
                if(DBG){printf("-------------seq end-----------\n");
                    printf("%d acquire %d cards(%d)(%d)\n",!term,cnum,c[!term],getN(!term));
                }
                thead=ttail=NULL;
                smode=cnum=0;
            }
            term=!term;
        }
    }
    int num=c[winner];
    printf("%d%3d\n",winner+1,num);
}
int main(){
    string s1;
    init();
    bool term;
    while(cin>>s1){
        if(s1=="#")break;
        term=1;
        head[0]=head[1]=tail[0]=tail[1]=NULL;
        rep(i,52){
            if(i>0)cin>>s1;
            Node *n=new Node(s1);
            n->next=head[term],head[term]=n;
            if(tail[term]==NULL)tail[term]=n;
            term=!term;
        }
        run();
    }
    
}

uva 10020 - Minimal coverage



 Minimal coverage 


The Problem

Given several segments of line (int the X axis) with coordinates [Li,Ri]. You are to choose the minimal amount of them, such they would completely cover the segment [0,M].

The Input


The first line is the number of test cases, followed by a blank line.
Each test case in the input should contains an integer M(1<=M<=5000), followed by pairs "Li Ri"(|Li|, |Ri|<=50000, i<=100000), each on a separate line. Each test case of input is terminated by pair "0 0".
Each test case will be separated by a single line.

The Output

For each test case, in the first line of output your programm should print the minimal number of line segments which can cover segment [0,M]. In the following lines, the coordinates of segments, sorted by their left end (Li), should be printed in the same format as in the input. Pair "0 0" should not be printed. If [0,M] can not be covered by given line segments, your programm should print "0"(without quotes).
Print a blank line between the outputs for two consecutive test cases.

Sample Input


2

1
-1 0
-5 -3
2 5
0 0

1
-1 0
0 1
0 0

Sample Output


0

1
0 1

Alex Gevak
September 10, 2000 (Revised 2-10-00, Antonio Sanchez)

O(n) solution 


#include<stdio.h>
#include<cstring>
#include<string>
#include<iostream>
#include<algorithm>
#include<vector>
#define REP(i, b, n) for (int i = b; i < n; i++)
#define rep(i, n) REP(i, 0, n)
#define DBG 0

using namespace std;

int M,A[5001];
vector<pair<int,int> >seq;
bool cmp(pair<int,int>a,pair<int,int>b){
if(a.first!=b.first)return a.first<b.first;
return a.second<b.second;
}
void ans(){
int cur=0,cm=-1,pick=-1,j;
vector<int>res;
rep(i,M+1){
if(DBG)printf("A %d %d\n",i,A[i]);
if(i<=cur){
if(A[i]>=0){
j=A[i];
if(seq[j].second>cur)
if(seq[j].second>cm){ //pick max
cm=seq[j].second,pick=j;
if(cm>=M)break;
}
}
}
else if(pick>=0)res.push_back(pick),cur=cm,cm=-1,i--;
else break; //fail
}
if(cm>0)res.push_back(pick);
if(cm>=M){
printf("%d\n",res.size());
rep(i,res.size())printf("%d %d\n",seq[res[i]].first,seq[res[i]].second);
}
else printf("0\n");
}
int main(){
int n,a,b;
bool ll=0;
cin>>n;
rep(i,n){
cin>>M;
seq.clear();memset(A,-1,sizeof(A));
while(scanf("%d%d",&a,&b)==2){
if(a==0&&b==0)break;
if(a<M&&b>0){if(a<0)a=0;seq.push_back(make_pair(a,b));}
}
rep(i,seq.size()){
int s1=seq[i].second-seq[i].first,s2=0,j;
if(A[seq[i].first]>=0)j=A[seq[i].first],s2=seq[j].second-seq[j].first;
if(s1>s2)A[seq[i].first]=i;
}
if(ll)printf("\n");ll=1;
ans();
}
}

uva 554 - Caesar Cypher



  Caesar Cypher 

One of the earliest encrypting systems is attributed to Julius Caesar: if the letter to be encrypted is the Nth letter in the alphabet, replace it with the (N+K)th where K is some fixed integer (Caesar used K = 3). We usually treat a space as zero and all arithemtic is then done modulo 27. Thus for K = 1 the message `ATTACK AT DAWN' becomes `BUUBDLABUAEBXO'.


Decrypting such a message is trivial since one only needs to try 26 different values of K. This process is aided by knowledge of the language, since then one can determine when the decrypted text forms recognisable words. If one does not know the language, then a dictionary would be necessary.


Write a program that will read in a dictionary and some encrypted text, determine the value of K that was used, and then decrypt the cyphertext to produce the original message. The original message contained only letters and spaces and has been encrypted using the above method. The most suitable value of K will be the one which produces the most matches with the words in the dictionary.

Input 

Input will consist of a dictionary and the encrypted text. The dictionary will consist of no more than 100 lines each containing a word in uppercase characters and not more than 20 characters in length. The dictionary portion will be terminated by a line consisting of a single `#'. The encrypted text will follow immediately and will consist of a single line containing no more than 250 characters. Note that the dictionary will not necessarily contain all the words in the original text, although it will certainly contain a large portion of them. It may also contain words that are not in the original text. The dictionary will not appear in any particular order.

Output 

Output will consist of the decrypted text. Lines should be as long as possible, but not exceeding 60 characters and no word may cross a linebreak.

Sample Input 

THIS
DAWN
THAT
THE
ZORRO
OTHER
AT
THING
#
BUUBDLA PSSPABUAEBXO

Sample Output 

ATTACK ZORRO AT DAWN



Miguel A. Revilla
1998-03-10
avoid leading and trailing spaces in each line 

#include<stdio.h>
#include<cstring>
#include<set>
#include<vector>
#include<iostream>
#define REP(i, b, n) for (int i = b; i < n; i++)
#define rep(i, n) REP(i, 0, n)
#define DBG 0

using namespace std;

string ts;
set<string>st;
vector<string>vc;
string trans(int c){
string s(ts.size(),'a');
int a;
rep(i,ts.size()){a=(ts[i]-'@'+c)%27,s[i]='@'+a;}
return s;
}
void println(){
string s;
rep(i,vc.size()){
s=vc[i];
if(s.size()){
while(s.size()&&s[s.size()-1]==' ')s.erase(s.size()-1,1);
if(s.size())printf("%s\n",s.c_str());
}
}
}
void ans(){
int cur=0,next,m=0,cnt;
string s,tmp,out;
rep(i,27){
s=trans(i);
cnt=cur=0;
while(1){
next=s.find('@',cur);
if(next==string::npos)tmp=s.substr(cur);
else tmp=s.substr(cur,next-cur);
cur=next+1;
if(st.count(tmp))cnt++;
if(next==string::npos)break;
}
if(cnt>m)m=cnt,out=s;
}
int size,c;
c=cur=0;
string cs;
while(out[out.size()-1]=='@')out.erase(out.size()-1,1);
rep(i,out.size()){
if(out[i]=='@'){
if(c==0)continue;
if(c<60)c++,cs+=' ';
else vc.push_back(cs),cs="",c=0;
continue;
}
next=out.find('@',cur);
if(next==string::npos)size=out.size()-cur,tmp=out.substr(cur);
else size=next-cur,tmp=out.substr(cur,next-cur);

if(c+size<=60)c+=size,cs+=tmp.c_str();
else vc.push_back(cs),cs="",cs=tmp.c_str(),c=size;
cur=next+1;
if(next==string::npos)break;
i=next-1;
}
vc.push_back(cs);
println();
}
int main(){
string s;
char chs[260];
while(cin>>s){if(s=="#")break;st.insert(s);}
scanf(" ");
if(fgets(chs,260,stdin)){
if(chs[strlen(chs)-1]=='\n')chs[strlen(chs)-1]='\0';
ts=chs;
rep(i,ts.size())if(ts[i]==' ')ts[i]='@';
if(DBG)printf("main %s\n",ts.c_str());
ans();
}
}