lzw的acm期末考试

为方便查找,可按ctrl+f,输入简短题目描述即可快速定位

Problem Description
Your task is to Calculate a + b.
Too easy?! Of course! I specially designed the problem for acm beginners.
You must have found that some problems have the same titles with this one, yes, all these problems were designed for the same aim.
Input
The input will consist of a series of pairs of integers a and b, separated by a space, one pair of integers per line.
Output
For each pair of input integers a and b you should output the sum of a and b in one line, and with one line of output for each line in input.
Sample Input
1 5
10 20
Sample Output
6
30

#include <stdio.h>
int main()
{
    int a,b,sum;
    while(scanf("%d%d",&a,&b)!=EOF)
    {
            sum=a+b;
            printf("%d\n",sum);
    
    }
return 0;
} 

Problem Description
Your task is to Calculate a + b.
Input
Input contains an integer N in the first line, and then N lines follow. Each line consists of a pair of integers a and b, separated by a space, one pair of integers per line.
Output
For each pair of input integers a and b you should output the sum of a and b in one line, and with one line of output for each line in input.
Sample Input
2
1 5
10 20
Sample Output
6
30

#include <stdio.h>
int main()
{
    int a,b,n,sum,i,j;
    while(scanf("%d",&n)!=EOF)
    {
        if(n==0)break;
        for(i=0;i<n;i++)
        {
            scanf("%d%d",&a,&b);
            sum=a+b;
            printf("%d\n",sum);
        }
    }
return 0;
} 

Calculate a + b.
Input
Input contains multiple test cases. Each test case contains a pair of integers a and b, one pair of integers per line. A test case containing 0 0 terminates the input and this test case is not to be processed.
Output
For each pair of input integers a and b you should output the sum of a and b in one line, and with one line of output for each line in input.
Sample Input
1 5
10 20
0 0
Sample Output
6
30

#include <stdio.h>
int main()
{
    int a,b,sum;
    while(scanf("%d%d",&a,&b)!=EOF)
    {
        if((a==0)&&(b==0)) break;
            sum=a+b;
            printf("%d\n",sum);
    
    }
return 0;
}

Problem Description
Your task is to Calculate the sum of some integers.
Input
Input contains multiple test cases. Each test case contains a integer N, and then N integers follow in the same line. A test case starting with 0 terminates the input and this test case is not to be processed.
Output
For each group of input integers you should output their sum in one line, and with one line of output for each line in input.
Sample Input
4 1 2 3 4
5 1 2 3 4 5
0
Sample Output
10
15

#include <stdio.h>
int main()
{
    int a,b,n,i;
    b=0;
    while(scanf("%d",&n)!=EOF)
    {
        if(n==0) break;
        for(i=0;i<n;i++)
        {
            scanf("%d",&a);
            b=b+a;
        }
        printf("%d\n",b);
        b=0;
    }
    return 0;
}

Problem Description Your task is to calculate the sum of some integers.

Input Input contains an integer N in the first line, and then N lines follow. Each line starts with a integer M, and then M integers follow in the same line.

Output For each group of input integers you should output their sum in one line, and with one line of output for each line in input.

Sample Input2
4 1 2 3 4
5 1 2 3 4 5
Sample Output10
15

#include <stdio.h>
int main()
{
    int m,n,a,sum=0,i,j;
    while(scanf("%d",&m)!=EOF)
    {
        if(m==0) break;
        for(i=0;i<m;i++)
        {
            scanf("%d",&n);
            for(j=0;j<n;j++)
            {
                scanf("%d",&a);
                sum+=a;
            }
            printf("%d\n",sum);
            sum=0;
        }
    }
    return 0;
}

Problem Description
Your task is to calculate the sum of some integers.

Input
Input contains multiple test cases, and one case one line. Each case starts with an integer N, and then N integers follow in the same line.

Output
For each test case you should output the sum of N integers in one line, and with one line of output for each line in input.

Sample Input
4 1 2 3 4
5 1 2 3 4 5
Sample Output
10
15

#include <stdio.h>
int main()
{
    int a,b,n,i;
    b=0;
    while(scanf("%d",&n)!=EOF)
    {
        for(i=0;i<n;i++)
        {
            scanf("%d",&a);
            b=b+a;
        }
        printf("%d\n",b);
        b=0;
    }
    return 0;
}

Problem Description
Your task is to Calculate a + b.

Input
The input will consist of a series of pairs of integers a and b, separated by a space, one pair of integers per line.

Output
For each pair of input integers a and b you should output the sum of a and b, and followed by a blank line.

Sample Input
1 5
10 20
Sample Output
6

30

#include <stdio.h>
int main()
{
    int a,b,sum=0;

        while(scanf("%d%d",&a,&b)!=EOF)
        {
          sum=a+b;
         printf("%d\n\n",sum);
     }
    return 0;
}

1096
Problem Description
Your task is to calculate the sum of some integers.
Input
Input contains an integer N in the first line, and then N lines follow. Each line starts with a integer M, and then M integers follow in the same line.
Output
For each group of input integers you should output their sum in one line, and you must note that there is a blank line between outputs.
Sample Input
3
4 1 2 3 4
5 1 2 3 4 5
3 1 2 3
Sample Output10

15

6

#include <stdio.h>
int main()
{
    int a[1000];
    int i,j,N,n,sum;
    
    for(i=0;i<1000;i++)      //给数组赋初值0 
    a[i]=0;
    
    scanf("%d",&N);
    for(i=0;i<N;i++)
    {
        scanf("%d",&n);
        sum=0;
        for(j=0;j<n;j++)
        {
          scanf("%d",&a[j]);
          sum+=a[j];
        }
        printf("%d\n",sum);
        if(i!=N-1)printf("\n");    
    }
    return 0;
} 

Problem Description Hey, welcome to HDOJ(Hangzhou Dianzi University Online Judge).

In this problem, your task is to calculate SUM(n) = 1 + 2 + 3 + … + n.

Input The input will consist of a series of integers n, one integer per line.

Output For each case, output SUM(n) in one line, followed by a blank line. You may assume the result will be in the range of 32-bit signed integer.

Sample Input1
100
Sample Output1

5050

#include <stdio.h>
int main()
{
   int b=0;
   long n,i;
   while(scanf("%d",&n)!=EOF)
   {
     for(i=n;i>0;i--)
     b+=i;
     printf("%d\n\n",b);
     b=0;
     }
     return 0;
}

Problem Description Given a positive integer N, you should output the most right digit of N^N.

Input The input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow.
Each test case contains a single positive integer N(1<=N<=1,000,000,000).

Output For each test case, you should output the rightmost digit of N^N.

Sample Input2
3
4
Sample Output7
6

Hint
In the first case, 3 * 3 * 3 = 27, so the rightmost digit is 7.
In the second case, 4 * 4 * 4 * 4 = 256, so the rightmost digit is 6.

#include <stdio.h> 

int main()
{
    int N;
    int a[25]={0,1,4,7,6,5,6,3,6,9,0,1,6,3,6,5,6,7,4,9,0};
    while(scanf("%d",&N)!=EOF)
    {        
        while(N--)
        {
            int n;
            scanf("%d",&n);
            printf("%d\n",a[n%20]);
        }
    }
    return 0;
}

Problem Description
Julius Caesar lived in a time of danger and intrigue. The hardest situation Caesar ever faced was keeping himself alive. In order for him to survive, he decided to create one of the first ciphers. This cipher was so incredibly sound, that no one could figure it out without knowing how it worked.
You are a sub captain of Caesar’s army. It is your job to decipher the messages sent by Caesar and provide to your general. The code is simple. For each letter in a plaintext message, you shift it five places to the right to create the secure message (i.e., if the letter is ‘A’, the cipher text would be ‘F’). Since you are creating plain text out of Caesar’s messages, you will do the opposite:

Cipher text
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Plain text
V W X Y Z A B C D E F G H I J K L M N O P Q R S T U

Only letters are shifted in this cipher. Any non-alphabetical character should remain the same, and all alphabetical characters will be upper case.

Input
Input to this problem will consist of a (non-empty) series of up to 100 data sets. Each data set will be formatted according to the following description, and there will be no blank lines separating data sets. All characters will be uppercase.

A single data set has 3 components:

Start line - A single line, “START”

Cipher message - A single line containing from one to two hundred characters, inclusive, comprising a single message from Caesar

End line - A single line, “END”

Following the final data set will be a single line, “ENDOFINPUT”.

Output
For each data set, there will be exactly one line of output. This is the original message by Caesar.

Sample Input
START
NS BFW, JAJSYX TK NRUTWYFSHJ FWJ YMJ WJXZQY TK YWNANFQ HFZXJX
END
START
N BTZQI WFYMJW GJ KNWXY NS F QNYYQJ NGJWNFS ANQQFLJ YMFS XJHTSI NS WTRJ
END
START
IFSLJW PSTBX KZQQ BJQQ YMFY HFJXFW NX RTWJ IFSLJWTZX YMFS MJ
END
ENDOFINPUT

Sample Output
IN WAR, EVENTS OF IMPORTANCE ARE THE RESULT OF TRIVIAL CAUSES
I WOULD RATHER BE FIRST IN A LITTLE IBERIAN VILLAGE THAN SECOND IN ROME
DANGER KNOWS FULL WELL THAT CAESAR IS MORE DANGEROUS THAN HE

#include <stdio.h>
#include <string.h>

char a[205],str[205];
char s[27]={'V','W','X','Y','Z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U'};
int main()
{
    while(gets(a))
    {
        if(strcmp(a,"ENDOFINPUT")==0)
        {
            break;
        }
        if(strcmp(a,"START")==0)
        {
            gets(str);
            int len=strlen(str);
            for(int i=0;i<len;i++)
            {
                if(str[i]>='A'&&str[i]<='Z')
                str[i]=s[str[i]-'A'];
            }
            printf("%s\n",str);
        }
    }
    return 0;
}

Problem Description
“今年暑假不AC?”
“是的。”
“那你干什么呢?”
“看世界杯呀,笨蛋!”
“@#$%^&*%…”

确实如此,世界杯来了,球迷的节日也来了,估计很多ACMer也会抛开电脑,奔向电视了。
作为球迷,一定想看尽量多的完整的比赛,当然,作为新时代的好青年,你一定还会看一些其它的节目,比如新闻联播(永远不要忘记关心国家大事)、非常6+7、超级女生,以及王小丫的《开心辞典》等等,假设你已经知道了所有你喜欢看的电视节目的转播时间表,你会合理安排吗?(目标是能看尽量多的完整节目)

Input
输入数据包含多个测试实例,每个测试实例的第一行只有一个整数n(n<=100),表示你喜欢看的节目的总数,然后是n行数据,每行包括两个数据Ti_s,Ti_e (1<=i<=n),分别表示第i个节目的开始和结束时间,为了简化问题,每个时间都用一个正整数表示。n=0表示输入结束,不做处理。

Output
对于每个测试实例,输出能完整看到的电视节目的个数,每个测试实例的输出占一行。

#include <stdio.h>
#include <algorithm>
using namespace std;
 
struct node 
{
    int t1;//电视开始时间 
    int t2;//电视的结束时间 
}a[105]; 
 
int cmp(node u,node v)
{// 对节目按照结束时间从小到大排序,如果结束的时间相同,则按照开始的时间从大到小的排序
    if(u.t2==v.t2)
        return u.t1>v.t1;
    return u.t2<v.t2;
}
 
int main()
{
    int n,i,j,k,t;
    while(scanf("%d",&n)&&n)
    {
        for(i=0;i<n;i++)
            scanf("%d%d",&a[i].t1,&a[i].t2);
            
        sort(a,a+n,cmp);//对时间进行快排 
        
        t=a[0].t2;
        k=1;
        for(i=1;i<n;i++)//如果开始时间比上一个的结束时间迟,则k++ 
        {
            if(a[i].t1>=t)//说明这个电视能看 
            {
                k++;
                t=a[i].t2;
            }
        }
        printf("%d\n",k); 
    }
    return 0;
}

Problem Description The famous ACM (Advanced Computer Maker) Company has rented a floor of a building whose shape is in the following figure.

The floor has 200 rooms each on the north side and south side along the corridor. Recently the Company made a plan to reform its system. The reform includes moving a lot of tables between rooms. Because the corridor is narrow and all the tables are big, only one table can pass through the corridor. Some plan is needed to make the moving efficient. The manager figured out the following plan: Moving a table from a room to another room can be done within 10 minutes. When moving a table from room i to room j, the part of the corridor between the front of room i and the front of room j is used. So, during each 10 minutes, several moving between two rooms not sharing the same part of the corridor will be done simultaneously. To make it clear the manager illustrated the possible cases and impossible cases of simultaneous moving.

For each room, at most one table will be either moved in or moved out. Now, the manager seeks out a method to minimize the time to move all the tables. Your job is to write a program to solve the manager’s problem.

Input The input consists of T test cases. The number of test cases ) (T is given in the first line of the input. Each test case begins with a line containing an integer N , 1<=N<=200 , that represents the number of tables to move. Each of the following N lines contains two positive integers s and t, representing that a table is to move from room number s to room number t (each room number appears at most once in the N lines). From the N+3-rd line, the remaining test cases are listed in the same manner as above.

Output The output should contain the minimum time in minutes to complete the moving, one per line.

#include<stdio.h>
int main()
{
    int a[200];
    int T,N,r,s,t,v,max,i,j,b,c;
    scanf("%d",&T);                //总测试组数 
    for(r=1;r<=T;r++)
    { 
      scanf("%d",&N);               //每一组的数据数量 
     for(i=0;i<=199;i++)
       a[i]=0;
      for(s=1;s<=N;s++)
      {
        scanf("%d%d",&b,&c);
        if(b>c)                           //保证i<j 
        {v=b;b=c;c=v;}      
        i=(b-1)/2;j=(c-1)/2;
        for(;i<=j;i++)
        a[i]=a[i]+1;                //递增1 
      }
          
        max=a[0];                     //输出数组中的最大值 
        for(t=1;t<200;t++)
      {
          if(max<a[t])
          max=a[t];
      }
      printf("%d\n",10*max);
     }
    return 0;    
} 

Problem Description There is a pile of n wooden sticks. The length and weight of each stick are known in advance. The sticks are to be processed by a woodworking machine in one by one fashion. It needs some time, called setup time, for the machine to prepare processing a stick. The setup times are associated with cleaning operations and changing tools and shapes in the machine. The setup times of the woodworking machine are given as follows:

(a) The setup time for the first wooden stick is 1 minute.
(b) Right after processing a stick of length l and weight w , the machine will need no setup time for a stick of length l’ and weight w’ if l<=l’ and w<=w’. Otherwise, it will need 1 minute for setup.

You are to find the minimum setup time to process a given pile of n wooden sticks. For example, if you have five sticks whose pairs of length and weight are (4,9), (5,2), (2,1), (3,5), and (1,4), then the minimum setup time should be 2 minutes since there is a sequence of pairs (1,4), (3,5), (4,9), (2,1), (5,2).

Input The input consists of T test cases. The number of test cases (T) is given in the first line of the input file. Each test case consists of two lines: The first line has an integer n , 1<=n<=5000, that represents the number of wooden sticks in the test case, and the second line contains n 2 positive integers l1, w1, l2, w2, …, ln, wn, each of magnitude at most 10000 , where li and wi are the length and weight of the i th wooden stick, respectively. The 2n integers are delimited by one or more spaces.

Output The output should contain the minimum setup time in minutes, one per line.

/*把所有木头按照[[长度]]从小到大排序,遍历一遍所有木头*/
/*遍历到某一根,就去找此木头前面是否有[[宽度]]<=当前宽度的*/
/*如果有多根,就取宽度最大的那一根*/
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
#define N 5010

struct Wood    //存储木头信息 
{
    int l,w;
}wood[N];

bool cmp(Wood a,Wood b)    
{
    if(a.l==b.l)
        return a.w<b.w;    //长度相等按重量排 
    else
        return a.l<b.l;
}

int main()
{
    int T,n;
    int dp[N],vis[N];
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        for(int i=0;i<n;i++)
            {
                scanf("%d %d",&wood[i].l,&wood[i].w);
                dp[i]=1;
                vis[i]=0;
            }
        sort(wood,wood+n,cmp);        
        int num=1,v;
        for(int i=1;i<n;i++)
        {
            v=-1;
            for(int j=i-1;j>=0;j--)
            {
                if(wood[i].w>=wood[j].w&&vis[j]==0)
                   {
                       if(v==-1||wood[j].w>wood[v].w)
                            {
                                dp[i]=dp[j]+1;
                                v=j;
                            } 
                   }
            }
            if(dp[i]==1)
                num++;
            vis[v]=1;
        }
        printf("%d\n",num);
    }
    return 0;
}

Here is a famous story in Chinese history.

“That was about 2300 years ago. General Tian Ji was a high official in the country Qi. He likes to play horse racing with the king and others.”

“Both of Tian and the king have three horses in different classes, namely, regular, plus, and super. The rule is to have three rounds in a match; each of the horses must be used in one round. The winner of a single round takes two hundred silver dollars from the loser.”

“Being the most powerful man in the country, the king has so nice horses that in each class his horse is better than Tian’s. As a result, each time the king takes six hundred silver dollars from Tian.”

“Tian Ji was not happy about that, until he met Sun Bin, one of the most famous generals in Chinese history. Using a little trick due to Sun, Tian Ji brought home two hundred silver dollars and such a grace in the next match.”

“It was a rather simple trick. Using his regular class horse race against the super class from the king, they will certainly lose that round. But then his plus beat the king’s regular, and his super beat the king’s plus. What a simple trick. And how do you think of Tian Ji, the high ranked official in China?”

Were Tian Ji lives in nowadays, he will certainly laugh at himself. Even more, were he sitting in the ACM contest right now, he may discover that the horse racing problem can be simply viewed as finding the maximum matching in a bipartite graph. Draw Tian’s horses on one side, and the king’s horses on the other. Whenever one of Tian’s horses can beat one from the king, we draw an edge between them, meaning we wish to establish this pair. Then, the problem of winning as many rounds as possible is just to find the maximum matching in this graph. If there are ties, the problem becomes more complicated, he needs to assign weights 0, 1, or -1 to all the possible edges, and find a maximum weighted perfect matching…

However, the horse racing problem is a very special case of bipartite matching. The graph is decided by the speed of the horses — a vertex of higher speed always beat a vertex of lower speed. In this case, the weighted bipartite matching algorithm is a too advanced tool to deal with the problem.

In this problem, you are asked to write a program to solve this special case of matching problem.

Input The input consists of up to 50 test cases. Each case starts with a positive integer n (n <= 1000) on the first line, which is the number of horses on each side. The next n integers on the second line are the speeds of Tian’s horses. Then the next n integers on the third line are the speeds of the king’s horses. The input ends with a line that has a single 0 after the last test case.

Output For each input case, output a line containing a single number, which is the maximum money Tian Ji will get, in silver dollars.

#include <stdio.h>
#include <algorithm>
using namespace std;
int t[1005];  //田忌 
int k[1005];  //国王 
int main(){
    int n;
    while(scanf("%d",&n)!=EOF&&n){
        int i,win=0,lose=0; 
        for(i=0;i<n;i++)
            scanf("%d",&t[i]);
        sort(t,t+n);       //从小到大排序 
        
        for(i=0;i<n;i++)
            scanf("%d",&k[i]);
        sort(k,k+n);
        int thead=0,tend=n-1;
        int    khead=0,kend=n-1;
        while(thead<=tend){
            if(t[tend]>k[kend])   //田忌最好的马比国王强 
                {
                    win++;
                    tend--;
                    kend--;
                }
            else if(t[thead]>k[khead])   //田忌差马比国王差马强 
            {
                win++;
                thead++;
                khead++;
            }
            else if(t[thead]<k[khead])    //差马打不过差马就直接打国王最强的马 
            {
                lose++;
                thead++;
                kend--;
            }
            else   //差马水平相等 
            {
                if(t[tend]>k[kend])   //田忌最好的马比国王强 
                {
                    win++;
                    tend--;
                    kend--;
                }
                else    //田忌最好的马不能赢国王的马 
                {
                    if(t[thead]<k[kend])  //最差的马打不过最好的马 
                    {
                        lose++;
                        thead++;
                        kend--;
                    }
                    else   //最坏的马和最好的马水平相当 
                    break;
                    
                }
            }
        }
        printf("%d\n",200*(win-lose)) ;
        
    }
    return 0;
}

Problem Description Ignatius has just come back school from the 30th ACM/ICPC. Now he has a lot of homework to do. Every teacher gives him a deadline of handing in the homework. If Ignatius hands in the homework after the deadline, the teacher will reduce his score of the final test, 1 day for 1 point. And as you know, doing homework always takes a long time. So Ignatius wants you to help him to arrange the order of doing homework to minimize the reduced score.
Input The input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow.
Each test case start with a positive integer N(1<=N<=15) which indicate the number of homework. Then N lines follow. Each line contains a string S(the subject’s name, each string will at most has 100 characters) and two integers D(the deadline of the subject), C(how many days will it take Ignatius to finish this subject’s homework).

Note: All the subject names are given in the alphabet increasing order. So you may process the problem much easier.

Output For each test case, you should output the smallest total reduced score, then give out the order of the subjects, one subject in a line. If there are more than one orders, you should output the alphabet smallest one.

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define N 1<<15
#define INF 0xfffffff

struct node{
    int end,cost;
    char name[105];
}dot[N];

struct node1{
    int now,pre;
    int time,ans;
}dp[N];

int n,m;

void solve(){
    int next,time,ans;
    for(int i=1;i<=m;i++)
        dp[i].ans=INF;
    dp[0].time=0;
    for(int i=0;i<=m;i++){
        for(int j=0;j<n;j++){
            if(!(i&(1<<j))){
                next=i|(1<<j);
                time=dp[i].time+dot[j].cost;
                ans=max(0,time-dot[j].end);
                ans+=dp[i].ans;
                if(ans<dp[next].ans){//如果找到更优解
                    dp[next].time=time;
                    dp[next].ans=ans;
                    dp[next].now=j;
                    dp[next].pre=i;
                }
            }
        }
    }
}

void output(int x){
    if(x==0)return;
    output(dp[x].pre);
    printf("%s\n",dot[dp[x].now].name);
}

int main()
{
    int t;
    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        for(int i=0;i<n;i++)
            scanf("%s%d%d",&dot[i].name,&dot[i].end,&dot[i].cost);
        m=(1<<n)-1;
        solve();
        printf("%d\n",dp[m].ans);
        output(m);
    }
    return 0;
}

Suppose that we have a square city with straight streets. A map of a city is a square board with n rows and n columns, each representing a street or a piece of wall.

A blockhouse is a small castle that has four openings through which to shoot. The four openings are facing North, East, South, and West, respectively. There will be one machine gun shooting through each opening.

Here we assume that a bullet is so powerful that it can run across any distance and destroy a blockhouse on its way. On the other hand, a wall is so strongly built that can stop the bullets.

The goal is to place as many blockhouses in a city as possible so that no two can destroy each other. A configuration of blockhouses is legal provided that no two blockhouses are on the same horizontal row or vertical column in a map unless there is at least one wall separating them. In this problem we will consider small square cities (at most 4x4) that contain walls through which bullets cannot run through.

The following image shows five pictures of the same board. The first picture is the empty board, the second and third pictures show legal configurations, and the fourth and fifth pictures show illegal configurations. For this board, the maximum number of blockhouses in a legal configuration is 5; the second picture shows one way to do it, but there are several other ways.

Your task is to write a program that, given a description of a map, calculates the maximum number of blockhouses that can be placed in the city in a legal configuration.

Input The input file contains one or more map descriptions, followed by a line containing the number 0 that signals the end of the file. Each map description begins with a line containing a positive integer n that is the size of the city; n will be at most 4. The next n lines each describe one row of the map, with a ‘.’ indicating an open space and an uppercase ‘X’ indicating a wall. There are no spaces in the input file.

Output For each test case, output one line containing the maximum number of blockhouses that can be placed in the city in a legal configuration.

#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
char ch[1005][1005];
int n,ans;
bool check(int x,int y)
    {
        for(int i=x-1;i>=0;i--)
        {
            if(ch[i][y]=='%')
                return false;
            if(ch[i][y]=='X')
                break;
        }
        for(int i=y-1;i>=0;i--)
        {
            if(ch[x][i]=='%')
                return false;
            if(ch[x][i]=='X')
                break;
        }
        return true;
    }
    
void dfs(int s,int sum)
    {
        if(s==n*n)
        {
            ans=max(ans,sum);
            return ;
        }
        int x=s/n;
        int y=s%n;
        if(ch[x][y]=='.'&&check(x,y))
        {
            ch[x][y]='%';
            dfs(s+1,sum+1);
            ch[x][y]='.';
        }
        dfs(s+1,sum);
    }
    
    int main()
    {
        while(scanf("%d",&n)!=EOF&&n)
        {
            getchar();
            ans=0;
            for(int i=0;i<n;i++)
            {
                scanf("%s",ch[i]);
            }
            dfs(0,0);
            printf("%d\n",ans);    
        }
        return 0;
    }

In the year 8888, the Earth is ruled by the PPF Empire . As the population growing , PPF needs to find more land for the newborns . Finally , PPF decides to attack Kscinow who ruling the Mars . Here the problem comes! How can the soldiers reach the Mars ? PPF convokes his soldiers and asks for their suggestions . “Rush … ” one soldier answers. “Shut up ! Do I have to remind you that there isn’t any road to the Mars from here!” PPF replies. “Fly !” another answers. PPF smiles :“Clever guy ! Although we haven’t got wings , I can buy some magic broomsticks from HARRY POTTER to help you .” Now , it’s time to learn to fly on a broomstick ! we assume that one soldier has one level number indicating his degree. The soldier who has a higher level could teach the lower , that is to say the former’s level > the latter’s . But the lower can’t teach the higher. One soldier can have only one teacher at most , certainly , having no teacher is also legal. Similarly one soldier can have only one student at most while having no student is also possible. Teacher can teach his student on the same broomstick .Certainly , all the soldier must have practiced on the broomstick before they fly to the Mars! Magic broomstick is expensive !So , can you help PPF to calculate the minimum number of the broomstick needed .
For example :
There are 5 soldiers (A B C D E)with level numbers : 2 4 5 6 4;
One method :
C could teach B; B could teach A; So , A B C are eligible to study on the same broomstick.
D could teach E;So D E are eligible to study on the same broomstick;
Using this method , we need 2 broomsticks.
Another method:
D could teach A; So A D are eligible to study on the same broomstick.
C could teach B; So B C are eligible to study on the same broomstick.
E with no teacher or student are eligible to study on one broomstick.
Using the method ,we need 3 broomsticks.
……

After checking up all possible method, we found that 2 is the minimum number of broomsticks needed.

Input Input file contains multiple test cases.
In a test case,the first line contains a single positive number N indicating the number of soldiers.(0<=N<=3000)
Next N lines :There is only one nonnegative integer on each line , indicating the level number for each soldier.( less than 30 digits);

Output For each case, output the minimum number of broomsticks on a single line.

#include<iostream>
#include<map>
using namespace std;
int a[3001];
int main()
{
    int n,i;
    map<int,int> m;
    while(~scanf("%d",&n))
    {
        m.clear();
        for(i=0;i<n;i++)
        {
            scanf("%d",&a[i]);
            m[a[i]]++;
        }
        map<int,int>::iterator it=m.begin();
        int max;
        max=it->second;
        for(;it!=m.end();it++)
        {
            if(max<it->second)
                max=it->second;
        }
        printf("%d\n",max);
    }
    return 0;
}

Problem Description FatMouse prepared M pounds of cat food, ready to trade with the cats guarding the warehouse containing his favorite food, JavaBean.
The warehouse has N rooms. The i-th room contains J[i] pounds of JavaBeans and requires F[i] pounds of cat food. FatMouse does not have to trade for all the JavaBeans in the room, instead, he may get J[i]* a% pounds of JavaBeans if he pays F[i]* a% pounds of cat food. Here a is a real number. Now he is assigning this homework to you: tell him the maximum amount of JavaBeans he can obtain.

Input The input consists of multiple test cases. Each test case begins with a line containing two non-negative integers M and N. Then N lines follow, each contains two non-negative integers J[i] and F[i] respectively. The last test case is followed by two -1’s. All integers are not greater than 1000.

Output For each test case, print in a single line a real number accurate up to 3 decimal places, which is the maximum amount of JavaBeans that FatMouse can obtain.

#include <stdio.h>
int main()
{
  double j[1000],f[1000],a[1000];
  int n,i,b,c,p,x;
  double m,k,t,sum;
  
  while(scanf("%lf",&m)!=EOF)
  {
        scanf("%d",&n);
        if(m==-1&&n==-1) break;
        
         for(i=0;i<n;i++)             //赋值 
         {
         scanf("%lf%lf",&j[i],&f[i]);
              a[i]=j[i]/f[i];
         }
 
     for(i=0;i<n;i++)   
          {   t=a[i];b=i;
             for(p=i+1;p<n;p++)   
                if(a[p]>t)       //划算的排在前面 
                {t=a[p];b=p;}
                if(b!=i)
                {
                    k=a[i];a[i]=a[b];a[b]=k;   
                    x=j[i];j[i]=j[b];j[b]=x;   
                    x=f[i];f[i]=f[b];f[b]=x; 
                }
           }   
           
        for(i=0;i<n;i++)   
            if(m>=f[i])   
            {   
                sum+=j[i];   
                m-=f[i];   
            }   
            else   
            {   
                sum+=a[i]*m;   
                break;   
            }   
    
    printf("%.3lf\n",sum);
    sum=0;
  }
  return 0;
}

Crixalis - Sand King used to be a giant scorpion(蝎子) in the deserts of Kalimdor. Though he’s a guardian of Lich King now, he keeps the living habit of a scorpion like living underground and digging holes.

Someday Crixalis decides to move to another nice place and build a new house for himself (Actually it’s just a new hole). As he collected a lot of equipment, he needs to dig a hole beside his new house to store them. This hole has a volume of V units, and Crixalis has N equipment, each of them needs Ai units of space. When dragging his equipment into the hole, Crixalis finds that he needs more space to ensure everything is placed well. Actually, the ith equipment needs Bi units of space during the moving. More precisely Crixalis can not move equipment into the hole unless there are Bi units of space left. After it moved in, the volume of the hole will decrease by Ai. Crixalis wonders if he can move all his equipment into the new hole and he turns to you for help.

Input The first line contains an integer T, indicating the number of test cases. Then follows T cases, each one contains N + 1 lines. The first line contains 2 integers: V, volume of a hole and N, number of equipment respectively. The next N lines contain N pairs of integers: Ai and Bi.
0<T<= 10, 0<V<10000, 0<N<1000, 0 <Ai< V, Ai <= Bi < 1000.

Output For each case output “Yes” if Crixalis can move all his equipment into the new hole or else output “No”.

#include<cstdio>
#include<algorithm>
using namespace std;
struct equip
{
    int a;    //所占空间 
    int b;    //周转空间 
    int v;    //v=b-a,用于衡量哪个应该先装
}e[1005];

bool cmp(equip x,equip y)  //按v从大到小排序,v同,按b从大到小排
{
    if(x.v!=y.v)
        return x.v>y.v;
    return x.b>y.b;
 }
 
int main()
{
    int T,n,V;
    int i,j;
    int flag,left,sum;
    scanf("%d",&T);
    while(T--)
    {
        flag=0;sum=0;
    //    printf("\n");
        scanf("%d %d",&V,&n);
        left=V;
        for(i=0;i<=n-1;i++)
        {
            scanf("%d%d",&e[i].a,&e[i].b);
            e[i].v=e[i].b-e[i].a;
            sum+=e[i].a;
            if(e[i].b>V) flag=1;
        }
        if(sum>V) 
            printf("No\n");
        else if(flag) 
            printf("No\n");
        else{
            sort(e,e+n,cmp);
            for(i=0;i<=n-1;i++)
            {
                if(left>=e[i].b)
                {
                    left=left-e[i].a;
                }
                else
                {
                    flag=1;break;
                }
            }
            if(!flag) printf("Yes\n");
            else printf("No\n");
        }
    }
    return 0;
}

Problem Description
Bob enjoys playing computer games, especially strategic games, but sometimes he cannot find the solution fast enough and then he is very sad. Now he has the following problem. He must defend a medieval city, the roads of which form a tree. He has to put the minimum number of soldiers on the nodes so that they can observe all the edges. Can you help him?

Your program should find the minimum number of soldiers that Bob has to put for a given tree.

The input file contains several data sets in text format. Each data set represents a tree with the following description:

the number of nodes
the description of each node in the following format
node_identifier:(number_of_roads) node_identifier1 node_identifier2 … node_identifier
or
node_identifier:(0)

The node identifiers are integer numbers between 0 and n-1, for n nodes (0 < n <= 1500). Every edge appears only once in the input data.

For example for the tree:

the solution is one soldier ( at the node 1).

The output should be printed on the standard output. For each given input data set, print one integer number in a single line that gives the result (the minimum number of soldiers). An example is given in the following table:

#include <stdio.h>
#include <vector>
#include <cstring>
using namespace std;

int visited[1505];  //标志该点是否被访问过
int result[1505];   //标志该点是否找到增广点
vector<int>vec[1505];

int find(int idx){
    for(int i = 0 ; i < vec[idx].size() ; i ++){
        int tempidx = vec[idx][i];
        if(visited[tempidx] == 0){
            visited[tempidx] = 1;
            if(result[tempidx] == -1 || find(result[tempidx]) == 1){
                result[tempidx] = idx;
                return 1;
            }
        }
    }
    return 0;
}

int main(){
    int n , i , j , idxs , num ,idxe , sum = 0;

    while(scanf("%d",&n) == 1){
        memset(visited , 0 , sizeof(visited));
        memset(result , -1 , sizeof(result));
        sum = 0 ;
        for(i = 0 ; i < n ; i ++)
            vec[i].clear();

        for(i = 0 ; i < n ; i ++){
            scanf("%d:(%d)",&idxs,&num);
            for( j = 0 ; j < num ; j ++){
                scanf("%d",&idxe);
                vec[idxs].push_back(idxe);
                vec[idxe].push_back(idxs);
            }
        }

        for(i = 0 ; i < n ; i ++){
            memset(visited , 0 , sizeof(visited));
            if(find(i))
                sum ++;
        }
        printf("%d\n",sum/2);
    }
    return 0;
}

Problem Description Bob is very interested in the data structure of a tree. A tree is a directed graph in which a special node is singled out, called the “root” of the tree, and there is a unique path from the root to each of the other nodes.

Bob intends to color all the nodes of a tree with a pen. A tree has N nodes, these nodes are numbered 1, 2, …, N. Suppose coloring a node takes 1 unit of time, and after finishing coloring one node, he is allowed to color another. Additionally, he is allowed to color a node only when its father node has been colored. Obviously, Bob is only allowed to color the root in the first try.

Each node has a “coloring cost factor”, Ci. The coloring cost of each node depends both on Ci and the time at which Bob finishes the coloring of this node. At the beginning, the time is set to 0. If the finishing time of coloring node i is Fi, then the coloring cost of node i is Ci * Fi.

For example, a tree with five nodes is shown in Figure-1. The coloring cost factors of each node are 1, 2, 1, 2 and 4. Bob can color the tree in the order 1, 3, 5, 2, 4, with the minimum total coloring cost of 33.

Given a tree and the coloring cost factor of each node, please help Bob to find the minimum possible total coloring cost for coloring all the nodes.

Input The input consists of several test cases. The first line of each case contains two integers N and R (1 <= N <= 1000, 1 <= R <= N), where N is the number of nodes in the tree and R is the node number of the root node. The second line contains N integers, the i-th of which is Ci (1 <= Ci <= 500), the coloring cost factor of node i. Each of the next N-1 lines contains two space-separated node numbers V1 and V2, which are the endpoints of an edge in the tree, denoting that V1 is the father node of V2. No edge will be listed twice, and all edges will be listed.

A test case of N = 0 and R = 0 indicates the end of input, and should not be processed.

Output For each test case, output a line containing the minimum total coloring cost required for Bob to color all the nodes.

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define maxn 1007
int total[maxn];
int c[maxn];
int fa[maxn];
int pre[maxn];
int num[maxn];
int find(int u){
    if(u == pre[u]) return u;
    return pre[u] = find(pre[u]);
}
int main(){
    int n,r;
    while(scanf("%d%d",&n,&r),n+r){
        for(int i = 1;i <= n; i++)
            scanf("%d",&c[i]);
        fa[r] = 0;
        int u,v;
        for(int i = 0;i < n-1;i++){
            scanf("%d%d",&u,&v);
            fa[v] = u;
        }
        for(int i = 0;i <= n; i++)
            pre[i] = i,num[i]=1;
        memset(total,0,sizeof(total));
 
        c[0] = 0;
        for(int i = 0;i < n; i++){
            u = 0;
            for(int j = 1;j <= n; j++){
                if(pre[j] == j){
                    if(u == 0 || c[u]*num[j]<c[j]*num[u]){
                        u = j;
                    }
                }
            }
            v = find(fa[u]);
            total[v] += num[v]*c[u]+total[u];
            num[v] += num[u];
            c[v] += c[u];
            pre[u] = v;
        }
        printf("%d\n",total[0]);
    }
    return 0;
}

Problem Description

The doggie found a bone in an ancient maze, which fascinated him a lot. However, when he picked it up, the maze began to shake, and the doggie could feel the ground sinking. He realized that the bone was a trap, and he tried desperately to get out of this maze.

The maze was a rectangle with sizes N by M. There was a door in the maze. At the beginning, the door was closed and it would open at the T-th second for a short period of time (less than 1 second). Therefore the doggie had to arrive at the door on exactly the T-th second. In every second, he could move one block to one of the upper, lower, left and right neighboring blocks. Once he entered a block, the ground of this block would start to sink and disappear in the next second. He could not stay at one block for more than one second, nor could he move into a visited block. Can the poor doggie survive? Please help him.

Input
The input consists of multiple test cases. The first line of each test case contains three integers N, M, and T (1 < N, M < 7; 0 < T < 50), which denote the sizes of the maze and the time at which the door will open, respectively. The next N lines give the maze layout, with each line containing M characters. A character is one of the following:

‘X’: a block of wall, which the doggie cannot enter;
‘S’: the start point of the doggie;
‘D’: the Door; or
‘.’: an empty block.
The input is terminated with three 0’s. This test case is not to be processed.

Output

For each test case, print in one line “YES” if the doggie can survive, or “NO” otherwise.

#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
int state[10][10], time, a, b, rx, ry, ax, ay;
char map[10][10];
int num[4][2] = {{0, 1}, {0, -1}, {1, 0}, { -1, 0}}, flag;
void DFS(int x, int y, int step)
{
	int i, kx, ky;

	if (x == ax && y == ay)
	{
		if (step == time)
		{
			flag = 1;
		}

		return;
	}

	if (step == time)
	{
		return;
	}

	if (map[x][y] == 'X')
	{
		return;
	}

	if (flag)
	{
		return;
	}

	for (i = 0; i < 4; i++)
	{
		kx = x + num[i][0];
		ky = y + num[i][1];

		if (kx < 0 || kx >= a || ky < 0 || ky >= b)
		{
			continue;
		}

		if (state[kx][ky] == 0)
		{
			state[kx][ky] = 1;
			DFS(kx, ky, step + 1);
			state[kx][ky] = 0;

			if (flag)
			{
				return;
			}
		}
	}
}
int main()
{
	int i, j;

	while (scanf("%d%d%d", &a, &b, &time), a || b || time)
	{
		memset(state, 0, sizeof(state));

		for (i = 0; i < a; i++)
		{
			getchar();

			for (j = 0; j < b; j++)
			{
				scanf("%c", &map[i][j]);

				if (map[i][j] == 'S')
				{
					rx = i;
					ry = j;
				}

				if (map[i][j] == 'D')
				{
					ax = i;
					ay = j;
				}
			}
		}

		getchar();

		if (abs(rx - ax) + abs(ry - ay) > time || (rx + ry + ax + ay + time) % 2 == 1)
		{
			printf("NO\n");
			continue;
		}

		flag = 0;
		state[rx][ry] = 1;
		DFS(rx, ry, 0);
		state[rx][ry] = 0;

		if (flag)
		{
			printf("YES\n");
		}
		else
		{
			printf("NO\n");
		}
	}

	return 0;
}

Problem Description

You’re in space.
You want to get home.
There are asteroids.
You don’t want to hit them.

Input

Input to this problem will consist of a (non-empty) series of up to 100 data sets. Each data set will be formatted according to the following description, and there will be no blank lines separating data sets.

A single data set has 5 components:

Start line - A single line, “START N”, where 1 <= N <= 10.

Slice list - A series of N slices. Each slice is an N x N matrix representing a horizontal slice through the asteroid field. Each position in the matrix will be one of two values:

‘O’ - (the letter “oh”) Empty space

‘X’ - (upper-case) Asteroid present

Starting Position - A single line, “A B C”, denoting the <A,B,C> coordinates of your craft’s starting position. The coordinate values will be integers separated by individual spaces.

Target Position - A single line, “D E F”, denoting the <D,E,F> coordinates of your target’s position. The coordinate values will be integers separated by individual spaces.

End line - A single line, “END”

The origin of the coordinate system is <0,0,0>. Therefore, each component of each coordinate vector will be an integer between 0 and N-1, inclusive.

The first coordinate in a set indicates the column. Left column = 0.

The second coordinate in a set indicates the row. Top row = 0.

The third coordinate in a set indicates the slice. First slice = 0.

Both the Starting Position and the Target Position will be in empty space.

Output

For each data set, there will be exactly one output set, and there will be no blank lines separating output sets.

A single output set consists of a single line. If a route exists, the line will be in the format “X Y”, where X is the same as N from the corresponding input data set and Y is the least number of moves necessary to get your ship from the starting position to the target position. If there is no route from the starting position to the target position, the line will be “NO ROUTE” instead.

A move can only be in one of the six basic directions: up, down, left, right, forward, back. Phrased more precisely, a move will either increment or decrement a single component of your current position vector by 1.

#include<iostream>
#include<cstring>
#include<string>
#include<queue>
using namespace std;
struct node {
 int x,y,z,step;
};
int sx,sy,sz,ex,ey,ez,n,map[15][15][15],vis[15][15][15],ans;
bool bfs() {
 queue<node> q;
 q.push(node{sx,sy,sz,0}); 
 int next[6][3]={{0,1,0},{0,-1,0},{1,0,0},{-1,0,0}, 
 {0,0,1},{0,0,-1}};//6个方向 
 node tmp;
 while(!q.empty()) {
  tmp=q.front();
  q.pop();
  if(tmp.x==ex&&tmp.y==ey&&tmp.z==ez) {
   ans=tmp.step;
   return true;
  }
  for(int i=0;i<6;i++) {
   int tx=tmp.x+next[i][0];
   int ty=tmp.y+next[i][1];
   int tz=tmp.z+next[i][2];
   if(tx<0||tx>=n||ty<0||ty>=n||tz<0||tz>=n) continue;
   if(vis[tz][tx][ty]||map[tz][tx][ty]) continue;
   q.push(node{tx,ty,tz,tmp.step+1});
   vis[tz][tx][ty]=1;//tz,tx,ty顺序很关键 
  }
 }
 return false;
}
int main() {
 string op;
 char ch;
 while(cin>>op>>n) {//op 用来过滤 START 
  for(int k=0;k<n;k++)
   for(int i=0;i<n;i++)
    for(int j=0;j<n;j++) {
     cin>>ch;
     map[k][i][j]=ch=='X'?1:0;
    }
  cin>>sx>>sy>>sz>>ex>>ey>>ez;
  cin>>op;//过滤 END
  memset(vis,0,sizeof(vis));
  if(bfs()) cout<<n<<' '<<ans<<endl;
  else cout<<"NO ROUTE"<<endl;
 }
 return 0;
} 

Problem Description

The GeoSurvComp geologic survey company is responsible for detecting underground oil deposits. GeoSurvComp works with one large rectangular region of land at a time, and creates a grid that divides the land into numerous square plots. It then analyzes each plot separately, using sensing equipment to determine whether or not the plot contains oil. A plot containing oil is called a pocket. If two pockets are adjacent, then they are part of the same oil deposit. Oil deposits can be quite large and may contain numerous pockets. Your job is to determine how many different oil deposits are contained in a grid.

Input

The input file contains one or more grids. Each grid begins with a line containing m and n, the number of rows and columns in the grid, separated by a single space. If m = 0 it signals the end of the input; otherwise 1 <= m <= 100 and 1 <= n <= 100. Following this are m lines of n characters each (not counting the end-of-line characters). Each character corresponds to one plot, and is either *', representing the absence of oil, or@’, representing an oil pocket.

Output

For each grid, output the number of distinct oil deposits. Two different pockets are part of the same oil deposit if they are adjacent horizontally, vertically, or diagonally. An oil deposit will not contain more than 100 pockets.

#include<iostream>
using namespace std;
char str[101][101];
int m,n,ccount;
int dir[8][2]={1,1,1,0,1,-1,0,1,0,-1,-1,1,-1,0,-1,-1};
void dfs(int a,int b)
{
 if(a>=0 &&  a<m &&  b>=0 && b<n && str[a][b]=='@')
  {
    str[a][b]='*';
      for(int i=0;i<8;i++)   
      dfs(a+dir[i][0],b+dir[i][1]);
       } 
}

int main()
{
 int i,j;
  while(cin>>m>>n && (m || n))
  {//m行 n列
    ccount=0;
      for(i=0;i<m;i++){
         for(j=0;j<n;j++){
             cin>>str[i][j];
                }
      }
        for(i=0;i<m;i++){
           for(j=0;j<n;j++){
               if(str[i][j]=='@'){
                      ccount++;
                      dfs(i,j);
                          }
                   }
            } 
     cout<<ccount<<endl;
    } 
  return 0;
  }

Problem Description

The digital root of a positive integer is found by summing the digits of the integer. If the resulting value is a single digit then that digit is the digital root. If the resulting value contains two or more digits, those digits are summed and the process is repeated. This is continued as long as necessary to obtain a single digit.

For example, consider the positive integer 24. Adding the 2 and the 4 yields a value of 6. Since 6 is a single digit, 6 is the digital root of 24. Now consider the positive integer 39. Adding the 3 and the 9 yields 12. Since 12 is not a single digit, the process must be repeated. Adding the 1 and the 2 yeilds 3, a single digit and also the digital root of 39.

Input

The input file will contain a list of positive integers, one per line. The end of the input will be indicated by an integer value of zero.

Output

For each integer in the input, output its digital root on a separate line of the output.

#include <stdio.h> 
int main(){
    int sum=0;
    char a;     
    while(a=getchar())//数据很大,用字符处理   
     {  
           if(a=='\n')        
           {      
                 if(!sum) 
                 return 0;       
                 printf("%d\n",sum%9?sum%9:9); //把所有位数的数字相加,然后 mod 9 可得 
                 sum=0;
                   }        
                 else if(a>='0' && a<='9')     
                    {       
                         sum+=a-'0';   
                       }  
         }  
    return 0;
}

Problem Description

Pass a year learning in Hangzhou, yifenfei arrival hometown Ningbo at finally. Leave Ningbo one year, yifenfei have many people to meet. Especially a good friend Merceki.
Yifenfei’s home is at the countryside, but Merceki’s home is in the center of city. So yifenfei made arrangements with Merceki to meet at a KFC. There are many KFC in Ningbo, they want to choose one that let the total time to it be most smallest.
Now give you a Ningbo map, Both yifenfei and Merceki can move up, down ,left, right to the adjacent road by cost 11 minutes.

Input

The input contains multiple test cases.
Each test case include, first two integers n, m. (2<=n,m<=200).
Next n lines, each line included m character.
‘Y’ express yifenfei initial position.
‘M’ express Merceki initial position.
‘#’ forbid road;
‘.’ Road.
‘@’ KCF

Output

For each test case output the minimum total time that both yifenfei and Merceki to arrival one of KFC.You may sure there is always have a KFC that can let them meet.

#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
#define MAX 210
#define INF 0x3f3f3f
using namespace std;
int bu1[MAX][MAX];//记录第一个人步数
int bu2[MAX][MAX];//记录第二个人步数
int p;
char map[MAX][MAX];
int vis[MAX][MAX];
int n,m;
struct node
{
    int x,y;
    int step;
};
int MIN(int x,int y)
{
    return x<y?x:y;
}
void bfs(int x1,int y1,int p)
{
    memset(vis,0,sizeof(vis));
    int j,i,ok=0;
    int move[4][2]={0,1,0,-1,1,0,-1,0};
    queue<node>q;
    node beg,end;
    beg.x=x1;
    beg.y=y1;
    beg.step=0;
    q.push(beg);
    while(!q.empty())
    {
        end=q.front();
        q.pop();
        if(map[end.x][end.y]=='@')//遇见@则表示到达终点
        {
            if(p==1)
            bu1[end.x][end.y]=end.step;
            else
            bu2[end.x][end.y]=end.step;
        }
        for(i=0;i<4;i++)
        {
            beg.x=end.x+move[i][0];
            beg.y=end.y+move[i][1];
            if(!vis[beg.x][beg.y]&&0<=beg.x&&beg.x<n&&0<=beg.y&&beg.y<m&&map[beg.x][beg.y]!='#')
            {
                vis[beg.x][beg.y]=1;
                beg.step=end.step+11;
                q.push(beg);
            }
        }
    }
}
int main()
{
    int sum,j,i,t,k,x1,x2,y1,y2,min;
    int s[11000];
    while(scanf("%d%d",&n,&m)!=EOF)
    {
         
        for(i=0;i<n;i++)
        {
            scanf("%s",map[i]);
        }
        for(i=0;i<n;i++)
        {
            for(j=0;j<m;j++)
            {
                if(map[i][j]=='Y')
                {
                    x1=i;y1=j;
                }
                else if(map[i][j]=='M')
                {
                    x2=i;y2=j;
                }
            }
        }
        memset(bu1,INF,sizeof(bu1));
        bfs(x1,y1,1);
        memset(bu2,INF,sizeof(bu2));
        bfs(x2,y2,2);
        min=INF;
        for(i=0;i<n;i++)
        {
            for(j=0;j<m;j++)
            {
                if(bu1[i][j]!=INF&&bu2[i][j]!=INF)
                {
                    min=MIN(bu1[i][j]+bu2[i][j],min);//取两者步数和的最小值
                }
            }
        }
        printf("%d\n",min);
    }
    return 0;     
}

Problem Description
Suppose that we have a square city with straight streets. A map of a city is a square board with n rows and n columns, each representing a street or a piece of wall.
A blockhouse is a small castle that has four openings through which to shoot. The four openings are facing North, East, South, and West, respectively. There will be one machine gun shooting through each opening.
Here we assume that a bullet is so powerful that it can run across any distance and destroy a blockhouse on its way. On the other hand, a wall is so strongly built that can stop the bullets.
The goal is to place as many blockhouses in a city as possible so that no two can destroy each other. A configuration of blockhouses is legal provided that no two blockhouses are on the same horizontal row or vertical column in a map unless there is at least one wall separating them. In this problem we will consider small square cities (at most 4x4) that contain walls through which bullets cannot run through.
The following image shows five pictures of the same board. The first picture is the empty board, the second and third pictures show legal configurations, and the fourth and fifth pictures show illegal configurations. For this board, the maximum number of blockhouses in a legal configuration is 5; the second picture shows one way to do it, but there are several other ways.
Your task is to write a program that, given a description of a map, calculates the maximum number of blockhouses that can be placed in the city in a legal configuration.

Input
The input file contains one or more map descriptions, followed by a line containing the number 0 that signals the end of the file. Each map description begins with a line containing a positive integer n that is the size of the city; n will be at most 4. The next n lines each describe one row of the map, with a ‘.’ indicating an open space and an uppercase ‘X’ indicating a wall. There are no spaces in the input file.
Output
For each test case, output one line containing the maximum number of blockhouses that can be placed in the city in a legal configuration.

#include<stdio.h>
#include<algorithm>
#include<cstring>
#include<queue>
const int Inf=0x3f3f3f3f;
typedef long long ll;
using namespace std;
int n, head[10005], mc[10005],vis[10005],cnt=0 ;
char a[10][10];
int map[10][10];
struct Edge{
    int to, next;
    
}edge[10005]; 
 
void init()
{
    cnt=0;
    memset(head, -1, sizeof(head));
    memset(mc, -1, sizeof(mc));
    memset(vis, 0, sizeof(vis));
    memset(map, 0, sizeof(map));
}
 
void add(int u, int t)
{
    edge[cnt].to=t;
    edge[cnt].next=head[u];
    head[u]=cnt;
    cnt++;
}
 
int dfs(int u)
{
    for(int i=head[u]; i!=-1; i=edge[i].next)
    {
        int v=edge[i].to;
        if(!vis[v])
        {

            vis[v]=1;
            if(mc[v]==-1||dfs(mc[v]))
            {
                mc[v]=u;
                return 1;
            }
        }
    }
    return 0;
}
 
int main()
{
    while(~scanf("%d", &n)&&n)
    {
        init();
        for(int i=0; i<n; i++)
        {
            scanf("%s", &a[i]);
        }
        int e[5]={0,0,0,0,0};
        for(int i=0; i<n; i++)
        {
            int d=0;
            for(int j=0; j<n; j++)
            {
                if(a[i][j]=='.')
                { 
                    add(i+d, j+e[j]);
                }
                if(a[i][j]=='X')
                {
                    e[j]+=n;
                    d+=n;
                }
            }
        }
        
        int s=0;
        for(int i=0; i<4*n; i++)
        {
            memset(vis, 0, sizeof(vis));
            s+=dfs(i);
        }
        printf("%d\n", s);
    }
} 

Problem Description

Famous Harry Potter,who seemd to be a normal and poor boy,is actually a wizard.Everything changed when he had his birthday of ten years old.A huge man called ‘Hagrid’ found Harry and lead him to a new world full of magic power.
If you’ve read this story,you probably know that Harry’s parents had left him a lot of gold coins.Hagrid lead Harry to Gringotts(the bank hold up by Goblins). And they stepped into the room which stored the fortune from his father.Harry was astonishing ,coz there were piles of gold coins.
The way of packing these coins by Goblins was really special.Only one coin was on the top,and three coins consisted an triangle were on the next lower layer.The third layer has six coins which were also consisted an triangle,and so on.On the ith layer there was an triangle have i coins each edge(totally i*(i+1)/2).The whole heap seemed just like a pyramid.Goblin still knew the total num of the layers,so it’s up you to help Harry to figure out the sum of all the coins.
Input
The input will consist of some cases,each case takes a line with only one integer N(0<N<2^31).It ends with a single 0.

Output
对于每个输入的N,输出一行,采用科学记数法来计算金币的总数(保留三位有效数字)

#include <stdio.h>
int main ()
{
    int n, i, k;
    double s;

    while (scanf ("%d", &n), n)
    {
        s = 1.0 * n * (n+1) * (n+2) / 6;
        k = 0;
        while (s >= 10)
        {
            s /= 10;
            k++;
        }
        printf ("%.2fE%d\n", s, k);
    }

    return 0;
}

Problem Description

Given a list of phone numbers, determine if it is consistent in the sense that no number is the prefix of another. Let’s say the phone catalogue listed these numbers:

  1. Emergency 911
  2. Alice 97 625 999
  3. Bob 91 12 54 26
    In this case, it’s not possible to call Bob, because the central would direct your call to the emergency line as soon as you had dialled the first three digits of Bob’s phone number. So this list would not be consistent.

Input

The first line of input gives a single integer, 1 <= t <= 40, the number of test cases. Each test case starts with n, the number of phone numbers, on a separate line, 1 <= n <= 10000. Then follows n lines with one unique phone number on each line. A phone number is a sequence of at most ten digits.

Output

For each test case, output “YES” if the list is consistent, or “NO” otherwise.


#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
using namespace std;
int main()
{
    vector<string>v;
    char a[10];
    string s;
    int t,n;
    scanf("%d",&t);
    while(t--)
    {
        cin>>n;
        v.clear();
        for(int i=0;i<n;i++)
        {
            scanf("%s",a);
            s=a;
            v.push_back(s);
        }
        sort(v.begin(),v.end());
        for(int i=0;i<n-1;i++)
        {
            if(v[i+1].find(v[i])==0)
            {
                printf("NO\n");
                goto eg;
            }
        }
        printf("YES\n");
        eg:;
    }
    return 0;
}

Problem Description

There is a pile of n wooden sticks. The length and weight of each stick are known in advance. The sticks are to be processed by a woodworking machine in one by one fashion. It needs some time, called setup time, for the machine to prepare processing a stick. The setup times are associated with cleaning operations and changing tools and shapes in the machine. The setup times of the woodworking machine are given as follows:
(a) The setup time for the first wooden stick is 1 minute.
(b) Right after processing a stick of length l and weight w , the machine will need no setup time for a stick of length l’ and weight w’ if l<=l’ and w<=w’. Otherwise, it will need 1 minute for setup.
You are to find the minimum setup time to process a given pile of n wooden sticks. For example, if you have five sticks whose pairs of length and weight are (4,9), (5,2), (2,1), (3,5), and (1,4), then the minimum setup time should be 2 minutes since there is a sequence of pairs (1,4), (3,5), (4,9), (2,1), (5,2).

Input

The input consists of T test cases. The number of test cases (T) is given in the first line of the input file. Each test case consists of two lines: The first line has an integer n , 1<=n<=5000, that represents the number of wooden sticks in the test case, and the second line contains n 2 positive integers l1, w1, l2, w2, …, ln, wn, each of magnitude at most 10000 , where li and wi are the length and weight of the i th wooden stick, respectively. The 2n integers are delimited by one or more spaces.

Output
The output should contain the minimum setup time in minutes, one per line.

#include<cstdio>
#include<algorithm>
using namespace std;
struct stick
{
    int len;
    int wei;
}a[5001];
bool used[5001];

bool cmp(stick k1,stick k2)       //按照长度从小到大排序,若长度相同按照重量递增排序
{
    if(k1.len==k2.len)
        return k1.wei<k2.wei;
    else
        return k1.len<k2.len;
}

int main()
{
    int T,n,i,j,st,count;
    bool flag;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        for(i=0;i<n;++i)
            scanf("%d%d",&a[i].len,&a[i].wei);
        sort(a,a+n,cmp);
        memset(used,false,sizeof(used));
        used[0]=true;
        st=0;       //记录第一个没有用过的木头
        count=0;
        while(st<n)
        {
            ++count;
            for(i=st+1,j=st,flag=true;i<n;++i)
            {
                if(used[i])
                    continue;
                if(a[j].len<=a[i].len&&a[j].wei<=a[i].wei)
                {
                    used[i]=true;
                    j=i;
                }
                else
                {
                    if(flag)
                    {
                        st=i;      //只记录第一个没用过的木头
                        flag=false;
                    }
                }
            }
            if(flag)    //说明都用过了
                break;
        }
        printf("%d\n",count);
    }
    return 0;
}

Problem Description

给定一个m × n (m行, n列)的迷宫,迷宫中有两个位置,gloria想从迷宫的一个位置走到另外一个位置,当然迷宫中有些地方是空地,gloria可以穿越,有些地方是障碍,她必须绕行,从迷宫的一个位置,只能走到与它相邻的4个位置中,当然在行走过程中,gloria不能走到迷宫外面去。令人头痛的是,gloria是个没什么方向感的人,因此,她在行走过程中,不能转太多弯了,否则她会晕倒的。我们假定给定的两个位置都是空地,初始时,gloria所面向的方向未定,她可以选择4个方向的任何一个出发,而不算成一次转弯。gloria能从一个位置走到另外一个位置吗?

Input
第1行为一个整数t (1 ≤ t ≤ 100),表示测试数据的个数,接下来为t组测试数据,每组测试数据中,
  第1行为两个整数m, n (1 ≤ m, n ≤ 100),分别表示迷宫的行数和列数,接下来m行,每行包括n个字符,其中字符’.‘表示该位置为空地,字符’*'表示该位置为障碍,输入数据中只有这两种字符,每组测试数据的最后一行为5个整数k, x1, y1, x2, y2 (1 ≤ k ≤ 10, 1 ≤ x1, x2 ≤ n, 1 ≤ y1, y2 ≤ m),其中k表示gloria最多能转的弯数,(x1, y1), (x2, y2)表示两个位置,其中x1,x2对应列,y1, y2对应行。
Output
 每组测试数据对应为一行,若gloria能从一个位置走到另外一个位置,输出“yes”,否则输出“no”。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int inf = 1000000;
char map[110][110];
int vis[110][110];//记录点的最优解;
int k, x1, x2, yy, y2, flag, m, n;
int dir[4][2] = { { 1, 0 },{ -1, 0 },{ 0, 1 },{ 0, -1 } };

struct node
{
	int x, y;
	int num;//次数
	int dir;//这个点由哪个方向来的;
};

bool cheak(int x, int y)//判断是否满足范围;
{
	if (x >= 0 && x < m && y >= 0 && y < n && map[x][y] != '*')
		return true;
	return false;
}

void bfs()
{
	queue<node>q;
	node temp, type;
	temp.x = x1;
	temp.y = yy;
	temp.num = -1;
	temp.dir = -1;
	q.push(temp);
	while (!q.empty())
	{
		temp = q.front();
		q.pop();
		if (temp.x == x2 && temp.y == y2 && temp.num <= k)
		{
			flag = 1;
			return;
		}
		for (int i = 0; i < 4; i++)
		{
			int fx = temp.x + dir[i][0];
			int fy = temp.y + dir[i][1];
			if (cheak(fx, fy))
			{
				if (temp.dir == -1)//开始 
				{
					type.dir = i;
					type.num = 0;
					type.x = fx;
					type.y = fy;
					if (vis[fx][fy] >= type.num)
					{
						vis[fx][fy] = temp.num;
						q.push(type);
					}
				}
				else
				{
					if (i == temp.dir)//新的坐标和它的上个比较,如果相同就不转弯;
					{
						type.dir = i;
						type.num = temp.num;
						type.x = fx;
						type.y = fy;
						if (type.num <= vis[fx][fy])
						{
							vis[fx][fy] = type.num;
							q.push(type);
						}
					}
					else
					{
						type.dir = i;
						type.num = temp.num + 1;
						type.x = fx;
						type.y = fy;
						if (type.num <= vis[fx][fy])
						{
							vis[fx][fy] = type.num;
							q.push(type);
						}
					}
				}
			}
		}
	}
	return;
}

int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		cin >> m >> n;
		for (int i = 0; i < m; i++)
			cin >> map[i];
		for (int i = 0; i < m; i++)
			for (int j = 0; j < n; j++)
				vis[i][j] = inf;
		cin >> k >> yy >> x1 >> y2 >> x2;
		x1 -= 1;//因为 图是按0开始的
		x2 -= 1;
		yy -= 1;
		y2 -= 1;
		flag = -1;
		if (x1 == x2 && yy == y2)
		{
			cout << "yes" << endl;
			continue;
		}
		bfs();

		if (flag == -1)
			cout << "no" << endl;
		else
			cout << "yes" << endl;
	}
	return 0;
}

Problem Description
给定两个正整数,计算这两个数的最小公倍数。
Input
输入包含多组测试数据,每组只有一行,包括两个不大于1000的正整数.
Output
对于每个测试用例,给出这两个数的最小公倍数,每个实例输出一行。

#include <iostream> 
using namespace std;

int gcd(int a,int b)
{
    if(b==0)
        return a;
    else 
        return gcd(b,a%b); 
}

int main()
{
    int a ,b;
    while(cin >> a >> b)
    {
        cout << a * b / gcd(a ,b) << endl;
    }    
} 

Problem Description

Give you three sequences of numbers A, B, C, then we give you a number X. Now you need to calculate if you can find the three numbers Ai, Bj, Ck, which satisfy the formula Ai+Bj+Ck = X.
Input
There are many cases. Every data case is described as followed: In the first line there are three integers L, N, M, in the second line there are L integers represent the sequence A, in the third line there are N integers represent the sequences B, in the forth line there are M integers represent the sequence C. In the fifth line there is an integer S represents there are S integers X to be calculated. 1<=L, N, M<=500, 1<=S<=1000. all the integers are 32-integers.
Iutput
For each case, firstly you have to print the case number as the form “Case d:”, then for the S queries, you calculate if the formula can be satisfied or not. If satisfied, you print “YES”, otherwise print “NO”.

#include<stdio.h>
#include<string.h>
#include<string>
#include<algorithm>
#include<iostream>
#include<math.h>
#define N 505
using namespace std;
__int64 num[N*N];
int mybinary_search(int len,int target)
{
    int L,R,mid=0;
    L=0;
    R=len-1;
    while(L<=R)
    {
        mid=(L+R)>>1;
        if(num[mid]>target)R=mid-1;
        else if(num[mid]<target)L=mid+1;
        else return mid;
    }
    return -1;
}
 
int main()
{
    int i,j,k,l,n,m,query,cnt1,cnt2;
    int a,b,c,flag;
    int  aa[505],bb[505],cc[505];
    cnt2=0;
    while(scanf("%d%d%d",&l,&m,&n)!=EOF)
    {
        cnt1=0;
        for(i=0; i<l; i++)scanf("%d",&aa[i]);
        for(i=0; i<m; i++)scanf("%d",&bb[i]);
        for(i=0; i<n; i++)scanf("%d",&cc[i]);
        for(i=0; i<l; i++)
            for(j=0; j<m; j++)
                num[cnt1++]=aa[i]+bb[j];
        sort(num,num+cnt1);
        sort(cc,cc+n);
        scanf("%d",&k);
        printf("Case %d:\n",++cnt2);
        while(k--)
        {
            scanf("%d",&query);
            flag=0;
            if(query<num[0]+cc[0]||query>num[cnt1-1]+cc[n-1])
            {
                printf("NO\n");
                continue;
            }
            for(j=0; j<n; j++)
            {
                if(mybinary_search(cnt1,query-cc[j])!=-1)
                {
                    printf("YES\n");
                    flag=1;
                    break;
                }
            }
            if(!flag)printf("NO\n");
        }
    }
 
    return 0;
}

Problem Description

There are another kind of Fibonacci numbers: F(0) = 7, F(1) = 11, F(n) = F(n-1) + F(n-2) (n>=2).

Input

Input consists of a sequence of lines, each containing an integer n. (n < 1,000,000).

Output

Print the word “yes” if 3 divide evenly into F(n).
Print the word “no” if not.

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
long long int a[1000001];
int main()
{
    int n,i;
    a[0]=7,a[1]=11;
    while(cin>>n)
    {
        for(i=2;i<=n;i++)
        {
            a[i]=a[i-1]+a[i-2];
            a[i]=a[i]/10+a[i]%10;
        }
        if(a[n]%3)
            cout<<"no"<<endl;
        else
            cout<<"yes"<<endl;
    }

return 0;
}

Problem Description

People in Silverland use square coins. Not only they have square shapes but also their values are square numbers. Coins with values of all square numbers up to 289 (=17^2), i.e., 1-credit coins, 4-credit coins, 9-credit coins, …, and 289-credit coins, are available in Silverland.
There are four combinations of coins to pay ten credits:
ten 1-credit coins,
one 4-credit coin and six 1-credit coins,
two 4-credit coins and two 1-credit coins, and
one 9-credit coin and one 1-credit coin.
Your mission is to count the number of ways to pay a given amount using coins of Silverland.
Input
The input consists of lines each containing an integer meaning an amount to be paid, followed by a line containing a zero. You may assume that all the amounts are positive and less than 300.
Output
For each of the given amount, one line containing a single integer representing the number of combinations of coins should be output. No other characters should appear in the output.

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
    int c1[310],c2[310];
    int i,j,k,n;
    while(cin>>n&&n)
    {
        for(i=0;i<=n;i++)
        {
            c1[i]=1;
            c2[i]=0;
        }
        for(i=2;i<=n;i++)
        {
            for(j=0;j<=n;j++)
            {
                for(k=0;j+k<=n;k+=i*i)
                    c2[j+k]+=c1[j];
            }
            for(j=0;j<=n;j++)
            {
                c1[j]=c2[j];
                c2[j]=0;
            }
        }
        cout<<c1[n]<<endl;
    }
}

Problem Description

Angel was caught by the MOLIGPY! He was put in prison by Moligpy. The prison is described as a N * M (N, M <= 200) matrix. There are WALLs, ROADs, and GUARDs in the prison.

Angel’s friends want to save Angel. Their task is: approach Angel. We assume that “approach Angel” is to get to the position where Angel stays. When there’s a guard in the grid, we must kill him (or her?) to move into the grid. We assume that we moving up, down, right, left takes us 1 unit time, and killing a guard takes 1 unit time, too. And we are strong enough to kill all the guards.

You have to calculate the minimal time to approach Angel. (We can move only UP, DOWN, LEFT and RIGHT, to the neighbor grid within bound, of course.)

	Input

First line contains two integers stand for N and M.
Then N lines follows, every line has M characters. “.” stands for road, “a” stands for Angel, and “r” stands for each of Angel’s friend.
Process to the end of the file.
Output

For each test case, your program should output a single integer, standing for the minimal time needed. If such a number does no exist, you should output a line containing “Poor ANGEL has to stay in the prison all his life.”

#include <iostream>
#include <cstdio>
#include <cstring>
#include<queue>
using namespace std;
struct node{
    int x,y,t;
    friend bool operator<(node n1,node n2){
        return n2.t<n1.t;
    }
};
int n,m;
char map[210][210];
int d[210][210];
int ax,ay,rx,ry;
node ft;
int mx[]={1,0,-1,0};
int my[]={0,-1,0,1};

int judge(int x,int y){
    if(x<0||x>=n||y<0||y>=m){
        return 0;
    }
    if(map[x][y]=='#'){
        return 0;
    }
    if(d[x][y]){
        return 0;
    }
    return 1;
}

void bfs(){
    priority_queue<node> q;
    ft.x=rx;
    ft.y=ry;
    ft.t=0;
    q.push(ft);
    d[rx][ry]=1;
    while(!q.empty()){
        ft=q.top();
        q.pop();
        //printf("%d,%d,%d\n",ft.x,ft.y,ft.t);
        int x=ft.x;
        int y=ft.y;
        if(x==ax&&y==ay){
            printf("%d\n",ft.t);
            return;
        }
        for(int i=0;i<4;i++){
            x=ft.x+mx[i];
            y=ft.y+my[i];
            if(!judge(x,y)){
                continue;
            }
            node nt;
            if(map[x][y]=='.'||map[x][y]=='a'){
                nt.x=x;
                nt.y=y;
                nt.t=ft.t+1;
                d[x][y]=1;
                q.push(nt);
            }else if(map[x][y]=='x'){
                nt.x=x;
                nt.y=y;
                nt.t=ft.t+2;
                d[x][y]=1;
                q.push(nt);
            }
        }
    }
    printf("Poor ANGEL has to stay in the prison all his life.\n");
}


int main()
{
    while(~scanf("%d%d",&n,&m)){
        memset(d,0,sizeof(d));
        for(int i=0;i<n;i++){
            scanf("%s",map[i]);
            for(int j=0;j<m;j++){
                if(map[i][j]=='a'){
                    ax=i,ay=j;
                }
                if(map[i][j]=='r'){
                    rx=i,ry=j;
                }
            }
        }
        bfs();
    }
    return 0;
}

Problem Description

Computer simulations often require random numbers. One way to generate pseudo-random numbers is via a function of the form
seed(x+1) = [seed(x) + STEP] % MOD
where ‘%’ is the modulus operator.
Such a function will generate pseudo-random numbers (seed) between 0 and MOD-1. One problem with functions of this form is that they will always generate the same pattern over and over. In order to minimize this effect, selecting the STEP and MOD values carefully can result in a uniform distribution of all values between (and including) 0 and MOD-1.
For example, if STEP = 3 and MOD = 5, the function will generate the series of pseudo-random numbers 0, 3, 1, 4, 2 in a repeating cycle. In this example, all of the numbers between and including 0 and MOD-1 will be generated every MOD iterations of the function. Note that by the nature of the function to generate the same seed(x+1) every time seed(x) occurs means that if a function will generate all the numbers between 0 and MOD-1, it will generate pseudo-random numbers uniformly with every MOD iterations.
If STEP = 15 and MOD = 20, the function generates the series 0, 15, 10, 5 (or any other repeating series if the initial seed is other than 0). This is a poor selection of STEP and MOD because no initial seed will generate all of the numbers from 0 and MOD-1.
Your program will determine if choices of STEP and MOD will generate a uniform distribution of pseudo-random numbers.

Input

Each line of input will contain a pair of integers for STEP and MOD in that order (1 <= STEP, MOD <= 100000).

Output

For each line of input, your program should print the STEP value right- justified in columns 1 through 10, the MOD value right-justified in columns 11 through 20 and either “Good Choice” or “Bad Choice” left-justified starting in column 25. The “Good Choice” message should be printed when the selection of STEP and MOD will generate all the numbers between and including 0 and MOD-1 when MOD numbers are generated. Otherwise, your program should print the message “Bad Choice”. After each output test set, your program should print exactly one blank line.

#include<iostream>
#include<string>
#include<iomanip>
using namespace std;

int p[100000];

bool allOnes(int mod){
    for(int i=0;i<mod;i++)
        if(p[i]==0 || p[i]>1)
            return false;
    return true;
}

int main()
{
    int step,mod;
    while(cin>>step>>mod)
    {

        memset(p,0,sizeof(p));
        for(int i=0;p[0]==0||i!=0;i=(i+step)%mod)
            p[i]++;
        cout<<setiosflags(ios::right)<<setw(10)<<step;
        cout<<setiosflags(ios::right)<<setw(10)<<mod;
        if(allOnes(mod))
            cout<<setw(4)<<""<<"Good Choice\n"<<endl;
        else
            cout<<setw(4)<<""<<"Bad Choice\n"<<endl;
    }
    return 0;
}

Problem Description

可怜的公主在一次次被魔王掳走一次次被骑士们救回来之后,而今,不幸的她再一次面临生命的考验。魔王已经发出消息说将在T时刻吃掉公主,因为他听信谣言说吃公主的肉也能长生不老。年迈的国王正是心急如焚,告招天下勇士来拯救公主。不过公主早已习以为常,她深信智勇的骑士LJ肯定能将她救出。
现据密探所报,公主被关在一个两层的迷宫里,迷宫的入口是S(0,0,0),公主的位置用P表示,时空传输机用#表示,墙用*表示,平地用.表示。骑士们一进入时空传输机就会被转到另一层的相对位置,但如果被转到的位置是墙的话,那骑士们就会被撞死。骑士们在一层中只能前后左右移动,每移动一格花1时刻。层间的移动只能通过时空传输机,且不需要任何时间。

Input

输入的第一行C表示共有C个测试数据,每个测试数据的前一行有三个整数N,M,T。 N,M迷宫的大小NM(1 <= N,M <=10)。T如上所意。接下去的前NM表示迷宫的第一层的布置情况,后N*M表示迷宫第二层的布置情况。

Output
如果骑士们能够在T时刻能找到公主就输出“YES”,否则输出“NO”。

#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
int n,m,T,ex,ey,ez;//e表示终点
char a[10+1][10+1][2+1];
bool vis[10+1][10+1][2+1];
struct node
{
    int xx,yy,zz,time;
}person;
bool check(int x,int y,int z)
{
    if(x>=1&&x<=n&&y>=1&&y<=m&&(z==1||z==2))//在界内
        if(a[x][y][z]!='*')//不为墙
            if(!vis[x][y][z])//未曾访问过
                return true;
    return false;
}
int rx[]={0,0,1,-1};
int ry[]={1,-1,0,0};
bool bfs()
{
    queue<node>Q;
    Q.push(person);
    node cur,next;
    while(!Q.empty())
    {
        cur=Q.front();
        Q.pop();
        vis[cur.xx][cur.yy][cur.zz]=true;
        if(cur.xx==ex&&cur.yy==ey&&cur.zz==ez&&cur.time<=T)
            return true;
        if(cur.time>T)
            break;
        if(a[cur.xx][cur.yy][cur.zz]=='#')
        {
            next.xx=cur.xx;
            next.yy=cur.yy;
            if(cur.zz==1)next.zz=2;
            else next.zz=1;
            if(check(next.xx,next.yy,next.zz))
                Q.push(next);
        }
        else
        {
            for(int i=0;i<4;i++)
            {
                next.xx=cur.xx+rx[i];
                next.yy=cur.yy+ry[i];
                next.zz=cur.zz;
                next.time=cur.time+1;
                if(check(next.xx,next.yy,next.zz))
                    Q.push(next);
            }
        }
    }
    return false;
}
int main()
{
    int K;
    cin>>K;
    while(K--)
    {
        cin>>n>>m>>T;
        memset(vis,false,sizeof(vis));
        for(int z=1;z<=2;z++)
        {
            for(int x=1;x<=n;x++)
            {
                for(int y=1;y<=m;y++)
                {
                    cin>>a[x][y][z];
                    if(a[x][y][z]=='S')
                    {
                        person.xx=x;
                        person.yy=y;
                        person.zz=z;
                        person.time=0;
                        vis[x][y][z]=true;
                    }//标记起点
                    else if(a[x][y][z]=='P')
                    {
                        ex=x;
                        ey=y;
                        ez=z;
                    }//标记终点
                }
            }
        }
        //接下来对时空传输机进行预处理
        for(int x=1;x<=n;x++)
        {
            for(int y=1;y<=m;y++)
            {
                if(a[x][y][1]=='#'&&a[x][y][2]=='#')
                {
                    a[x][y][1]='*';
                    a[x][y][2]='*';
                }
                else if(a[x][y][1]=='#'&&a[x][y][2]=='*')
                {
                    a[x][y][1]='*';
                }
                else if(a[x][y][2]=='#'&&a[x][y][1]=='*')
                {
                    a[x][y][2]='*';
                }
            }
        }
        if(bfs())
            cout<<"YES"<<endl;
        else 
            cout<<"NO"<<endl;
    }
    return 0;
}

Problem Description

The least common multiple (LCM) of a set of positive integers is the smallest positive integer which is divisible by all the numbers in the set. For example, the LCM of 5, 7 and 15 is 105.

Input

Input will consist of multiple problem instances. The first line of the input will contain a single integer indicating the number of problem instances. Each instance will consist of a single line of the form m n1 n2 n3 … nm where m is the number of integers in the set and n1 … nm are the integers. All integers will be positive and lie within the range of a 32-bit integer.

Output

For each problem instance, output a single line containing the corresponding LCM. All results will lie in the range of a 32-bit integer.

#include<iostream>
using namespace std;
int check(int a,int b)//辗转相除 与大小无关
{
    if(b==0) return a;
    return check(b,a%b);
}
int main()
{
    int n;
    int m;
    int x,y;
    int sum;
    while(scanf("%d",&n)!=EOF)
    {
        for(int i=0;i<n;i++)
        {
            sum=0;
            x=1;//处理一个输入数据的情况
            cin>>m;
            for(int j=0;j<m;j++)
            {
            cin>>y;
            sum=x/check(x,y)*y;    //最小公约数与顺序无关    
            x=sum;            
            }
            cout<<sum<<endl;       
        }    
    }

    return 0;
}

Problem Description
Given a positive integer N, you should output the most right digit of N^N.
Input
The input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow.
Each test case contains a single positive integer N(1<=N<=1,000,000,000).
Output
For each test case, you should output the rightmost digit of N^N.

#include<stdio.h>
#include<stdlib.h>
int main(){
    int n,m,i,j,a,b;    
 long long int sum=1;    
 while(~scanf("%d",&n))  
   {
     for(i=0;i<n;i++)        
   {    
      scanf("%d",&m);            
   b=m%20;            
   if(b==0)             
      b=10;           
   a=1;            
   for(j=0;j<b;j++)            
   {            
       sum=a*b;                
    a=sum%10;            
   }            
   
   printf("%d\n",a);     
    }   
   }    
   return 0;
}

Problem Description

Ignatius bought a land last week, but he didn’t know the area of the land because the land is enclosed by a parabola and a straight line. The picture below shows the area. Now given all the intersectant points shows in the picture, can you tell Ignatius the area of the land?

Note: The point P1 in the picture is the vertex of the parabola.
Input

The input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow.
Each test case contains three intersectant points which shows in the picture, they are given in the order of P1, P2, P3. Each point is described by two floating-point numbers X and Y(0.0<=X,Y<=1000.0).

Output
For each test case, you should output the area of the land, the result should be rounded to 2 decimal places.

#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int main()
{
    int zong;
    cin>>zong;
    while(zong--)
    {
        double x1,y1,x2,y2,x3,y3;
        cin>>x1>>y1>>x2>>y2>>x3>>y3;
        double t1=(x2*x2-x3*x3)*(y2-y1)-(x2*x2-x1*x1)*(y2-y3);
        double t2=(x2*x2-x3*x3)*(x2-x1)-(x2*x2-x1*x1)*(x2-x3);
        double b=t1/t2;
        double a=(y2-y1-b*(x2-x1))/(x2*x2-x1*x1);
        double c=y1-a*x1*x1-b*x1;
        double k=(y2-y3)/(x2-x3);
        double d=y2-k*x2;
        double s1=1.0/3.0*a*(x3*x3*x3-x2*x2*x2)+1.0/2*b*(x3*x3-x2*x2)+c*(x3-x2);
        double s2=(k*(x2+x3)+2*d)*(x3-x2)*1.0/2.0;
        double s=s1-s2;
        printf("%.2lf\n",s);
    }
    return 0;
}

Problem Description

假设:
S1 = 1
S2 = 12
S3 = 123
S4 = 1234

S9 = 123456789
S10 = 1234567891
S11 = 12345678912

S18 = 123456789123456789

现在我们把所有的串连接起来
S = 1121231234…123456789123456789112345678912…
那么你能告诉我在S串中的第N个数字是多少吗?
Input
输入首先是一个数字K,代表有K次询问。
接下来的K行每行有一个整数N(1 <= N < 2^31)。
Output
对于每个N,输出S中第N个对应的数字.

#include<iostream>
#include<cmath>
using namespace std;
int main()
{
    long long t,n,s,i;
    cin>>t;
    while(t--)
    {
        cin>>n;
        for(i=sqrt(2*n);i>0;i--)
        {
            if(((i*(i+1))/2<n))
                break;
        }
        s=n-((i*(i+1))/2);
        if(s%9==0)
            cout<<9<<endl;
        else
            cout<<s%9<<endl;
    }
    return 0;
}

Problem Description

The 15-puzzle has been around for over 100 years; even if you don’t know it by that name, you’ve seen it. It is constructed with 15 sliding tiles, each with a number from 1 to 15 on it, and all packed into a 4 by 4 frame with one tile missing. Let’s call the missing tile ‘x’; the object of the puzzle is to arrange the tiles so that they are ordered as:

1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 x

where the only legal operation is to exchange ‘x’ with one of the tiles with which it shares an edge. As an example, the following sequence of moves solves a slightly scrambled puzzle:

1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
5 6 7 8 5 6 7 8 5 6 7 8 5 6 7 8
9 x 10 12 9 10 x 12 9 10 11 12 9 10 11 12
13 14 11 15 13 14 11 15 13 14 x 15 13 14 15 x
r-> d-> r->

The letters in the previous row indicate which neighbor of the ‘x’ tile is swapped with the ‘x’ tile at each step; legal values are ‘r’,‘l’,‘u’ and ‘d’, for right, left, up, and down, respectively.

Not all puzzles can be solved; in 1870, a man named Sam Loyd was famous for distributing an unsolvable version of the puzzle, and
frustrating many people. In fact, all you have to do to make a regular puzzle into an unsolvable one is to swap two tiles (not counting the missing ‘x’ tile, of course).

In this problem, you will write a program for solving the less well-known 8-puzzle, composed of tiles on a three by three
arrangement.

Input

You will receive, several descriptions of configuration of the 8 puzzle. One description is just a list of the tiles in their initial positions, with the rows listed from top to bottom, and the tiles listed from left to right within a row, where the tiles are represented by numbers 1 to 8, plus ‘x’. For example, this puzzle

1 2 3
x 4 6
7 5 8

is described by this list:

1 2 3 x 4 6 7 5 8

Output

You will print to standard output either the word ``unsolvable’’, if the puzzle has no solution, or a string consisting entirely of the letters ‘r’, ‘l’, ‘u’ and ‘d’ that describes a series of moves that produce a solution. The string should include no spaces and start at the beginning of the line. Do not print a blank line between cases.

#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<map>
#include<queue>
#include<stack>
#include<vector>
#include<algorithm>
#include<cstring>
#include<string>
#include<iostream>
const int MAXN=500000+10;
const int MAXNHASH=500000+10;
using namespace std;
typedef int State[9];
State st[MAXN];
int goal[9];
int vis[370000];
int fact[9];
int fa[MAXN];
int dir[MAXN];
int codestart,codeend;
const int dx[]={-1,1,0,0};
const int dy[]={0,0,-1,1};
char cal[5]="durl";
 
void init_lookup_table()
{
 fact[0]=1;
 for(int i=1; i<9; i++){
  fact[i]=fact[i-1]*i;
 }
}
 
int Code(State &s)
{
 int code=0;
 for(int i=0; i<9; i++){
  int cnt=0;
  for(int j=i+1; j<9; j++){
   if(s[j]<s[i]) cnt++; 
  }
  code+=fact[8-i]*cnt;
 }
 return code;
}
 
void bfs()
{
 memset(fa,0,sizeof(fa));
 memset(vis,0,sizeof(vis));
 int front=1, rear=2;
 while(front<rear)
 {
  //cout<<front<<endl;
  State& s=st[front];
  //if(memcmp(goal, s, sizeof(s))==0) return front;
  int z;
  for(z=0; z<9; z++) if(!s[z]) break;
  int x=z/3, y=z%3;
  for(int i=0; i<4; i++){
   int newx=x+dx[i];
   int newy=y+dy[i];
   int newz=newx*3+newy;
   if(newx>=0 && newx<3 && newy>=0 && newy<3){
    State&t =st[rear];
    memcpy(t,s,sizeof(s));
    t[newz]=s[z];
    t[z]=s[newz];
    int code=Code(t);
    int code1=Code(s);
    if(!vis[code]){
     vis[code]=1;
     fa[code]=code1;
     dir[code]=i;
     rear++;
    }
   }
  }
  front++;
 }
}
 
void print(int num)
{
 if(num!=codeend){
  cout<<cal[dir[num]];
  print(fa[num]);
 }
}
 
int main()
{
 //freopen("in.txt","r",stdin);
 init_lookup_table();
 char ch;
 for(int i=0; i<8; i++) st[1][i]=i+1;
 st[1][8]=0;
 codeend=Code(st[1]);
 vis[codeend]=1;
 bfs();
 while(cin>>ch)
 {
  if(ch=='x') goal[0]=ch-120;
  else goal[0]=ch-'0';
  for(int i=1; i<9; i++){
   cin>>ch;
   if(ch=='x') goal[i]=ch-120;
   else goal[i]=ch-'0';
  }
  codestart=Code(goal);
  if(vis[codestart]){
   print(codestart);
   cout<<endl;
  }
  else cout<<"unsolvable"<<endl;
 }
 return 0;
}

Problem Description

It is written in the Book of The Lady: After the Creation, the cruel god Moloch rebelled against the authority of Marduk the Creator.Moloch stole from Marduk the most powerful of all the artifacts of the gods, the Amulet of Yendor, and he hid it in the dark cavities of Gehennom, the Under World, where he now lurks, and bides his time.

Your goddess The Lady seeks to possess the Amulet, and with it to gain deserved ascendance over the other gods.

You, a newly trained Rambler, have been heralded from birth as the instrument of The Lady. You are destined to recover the Amulet for your deity, or die in the attempt. Your hour of destiny has come. For the sake of us all: Go bravely with The Lady!

If you have ever played the computer game NETHACK, you must be familiar with the quotes above. If you have never heard of it, do not worry. You will learn it (and love it) soon.

In this problem, you, the adventurer, are in a dangerous dungeon. You are informed that the dungeon is going to collapse. You must find the exit stairs within given time. However, you do not want to leave the dungeon empty handed. There are lots of rare jewels in the dungeon. Try collecting some of them before you leave. Some of the jewels are cheaper and some are more expensive. So you will try your best to maximize your collection, more importantly, leave the dungeon in time.

Input

Standard input will contain multiple test cases. The first line of the input is a single integer T (1 <= T <= 10) which is the number of test cases. T test cases follow, each preceded by a single blank line.

The first line of each test case contains four integers W (1 <= W <= 50), H (1 <= H <= 50), L (1 <= L <= 1,000,000) and M (1 <= M <= 10). The dungeon is a rectangle area W block wide and H block high. L is the time limit, by which you need to reach the exit. You can move to one of the adjacent blocks up, down, left and right in each time unit, as long as the target block is inside the dungeon and is not a wall. Time starts at 1 when the game begins. M is the number of jewels in the dungeon. Jewels will be collected once the adventurer is in that block. This does not cost extra time.

The next line contains M integers,which are the values of the jewels.

The next H lines will contain W characters each. They represent the dungeon map in the following notation:

[*] marks a wall, into which you can not move;
[.] marks an empty space, into which you can move;
[@] marks the initial position of the adventurer;
[<] marks the exit stairs;
[A] - [J] marks the jewels.

Output

Results should be directed to standard output. Start each case with “Case #:” on a single line, where # is the case number starting from 1. Two consecutive cases should be separated by a single blank line. No blank line should be produced after the last test case.

If the adventurer can make it to the exit stairs in the time limit, print the sentence “The best score is S.”, where S is the maximum value of the jewels he can collect along the way; otherwise print the word “Impossible” on a single line.

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
char mp[60][60];
int T,n,m,t,p,val[15],ans;
int dir[4][2]={1,0,-1,0,0,1,0,-1};
bool vis[55][55][1<<10],cost[55][55];
struct node{
    int x,y,cnt,sum,sta;
    node(){}
    node(int a,int b,int c,int d,int e):x(a),y(b),cnt(c),sum(d),sta(e){}
}no1,no2;
void bfs(int px,int py){
    memset(vis,0,sizeof(vis));
    memset(cost,0,sizeof(cost));
    no1=node(px,py,0,0,0);
    queue<node>q;
    q.push(no1);
    vis[px][py][0]=1;
    while(!q.empty()){
        no1=q.front();q.pop();
        if(no1.cnt>t) continue;
        if(mp[no1.x][no1.y]=='<'){
            if(ans==-1) ans=0;
            ans=max(ans,no1.sum);
        }
        for(int i=0;i<4;i++){
            int x=no1.x+dir[i][0],y=no1.y+dir[i][1];
            if(x<0||x>=n||y<0||y>=m) continue;
            if(mp[x][y]=='*') continue;
            if('A'<=mp[x][y]&&mp[x][y]<='J'){
                if(no1.sta&(1<<(mp[x][y]-'A'))){
                    if(vis[x][y][no1.sta]) continue;
                    vis[x][y][no1.sta]=1;
                    no2=node(x,y,no1.cnt+1,no1.sum,no1.sta);
                    q.push(no2);continue;
                }
                int tmp=no1.sta^(1<<(mp[x][y]-'A'));
                if(vis[x][y][tmp]) continue;
                vis[x][y][tmp]=1;
                no2=node(x,y,no1.cnt+1,no1.sum+val[mp[x][y]-'A'],tmp);
                q.push(no2);
            }
            else{
                if(vis[x][y][no1.sta]) continue;
                vis[x][y][no1.sta]=1;
                no2=node(x,y,no1.cnt+1,no1.sum,no1.sta);
                q.push(no2);
            }
        }
    }
}
int main()
{
    scanf("%d",&T);
    for(int cas=1;cas<=T;cas++){
        int px,py;
        scanf("%d%d%d%d",&m,&n,&t,&p);
        for(int i=0;i<p;i++) scanf("%d",&val[i]);
        for(int i=0;i<n;i++){
            scanf("%s",mp[i]);
            for(int j=0;j<m;j++)
                if(mp[i][j]=='@') {px=i;py=j;}
        }
        ans=-1;
        bfs(px,py);
        printf("Case %d:\n",cas);
        if(ans==-1) printf("Impossible\n");
        else printf("The best score is %d.\n",ans);
        if(cas!=T) printf("\n");
    }
    return 0;
}

Problem Description

Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.

  • Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
  • Teleporting: FJ can move from any point X to the point 2 × X in a single minute.

If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?

Input

Line 1: Two space-separated integers: N and K

Output

Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.

#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
struct node {
	int x,step;
}temp, p;
bool vis[10000005];
int d[2] = {1,-1};
int bfs(int a, int b)
{
	memset(vis,false,sizeof(vis));
	queue<node> q;
	while (!q.empty())   q.pop();
	p.x = a;
	p.step = 0;
	q.push(p);
	vis[a] = true;
	while (q.size()) {
		p = q.front();
		q.pop();
		if(p.x == b)  return p.step;
		for(int i = 0; i < 3; i++) {
			if (i == 2)	 temp.x = p.x * 2;
			else	temp.x = p.x + d[i];
			if (temp.x < 0 || vis[temp.x] || temp.x>100000)	continue;
			vis[temp.x] = true;
			temp.step = p.step + 1;
			q.push(temp);
		}
	}
	return -1;
}
int main()
{
	int n, k;
	while (scanf("%d %d", &n, &k) != EOF)
	{
		int ans = bfs(n,k);
		printf("%d\n", ans);
	}
	return 0;
}

Problem Description

Some problems are difficult to solve but have a simplification that is easy to solve. Rather than deal with the difficulties of constructing a model of the Earth (a somewhat oblate spheroid), consider a pre-Columbian flat world that is a 500 kilometer 500 kilometer square.
In the model used in this problem, the flat world consists of several warring kingdoms. Though warlike, the people of the world are strict isolationists; each kingdom is surrounded by a high (but thin) wall designed to both protect the kingdom and to isolate it. To avoid fights for power, each kingdom has its own electric power plant.
When the urge to fight becomes too great, the people of a kingdom often launch missiles at other kingdoms. Each SCUD missile (anitary leansing niversal estroyer) that lands within the walls of a kingdom destroys that kingdom’s power plant (without loss of life).
Given coordinate locations of several kingdoms (by specifying the locations of houses and the location of the power plant in a kingdom) and missile landings you are to write a program that determines the total area of all kingdoms that are without power after an exchange of missile fire.
In the simple world of this problem kingdoms do not overlap. Furthermore, the walls surrounding each kingdom are considered to be of zero thickness. The wall surrounding a kingdom is the minimal-perimeter wall that completely surrounds all the houses and the power station that comprise a kingdom; the area of a kingdom is the area enclosed by the minimal-perimeter thin wall.
There is exactly one power station per kingdom.
There may be empty space between kingdoms.

Input

The input is a sequence of kingdom specifications followed by a sequence of missile landing locations.

A kingdom is specified by a number N ( 3≤N≤10) on a single line which indicates the number of sites in this kingdom. The next line contains the x and y coordinates of the power station, followed by N-1 lines of x, y pairs indicating the locations of homes served by this power station. A value of -1 for N indicates that there are no more kingdoms. There will be at least one kingdom in the data set.

Following the last kingdom specification will be the coordinates of one or more missile attacks, indicating the location of a missile landing. Each missile location is on a line by itself. You are to process missile attacks until you reach the end of the file.

Locations are specified in kilometers using coordinates on a 500 km by 500 km grid. All coordinates will be integers between 0 and 500 inclusive. Coordinates are specified as a pair of integers separated by white-space on a single line. The input file will consist of up to 20 kingdoms, followed by any number of missile attacks.

Output

The output consists of a single number representing the total area of all kingdoms without electricity after all missile attacks have been processed. The number should be printed with (and correct to) two decimal places

#include <algorithm>
#include <functional>
#include <iomanip>
#include <iostream>
#include <vector>
#include <math.h>
 
using namespace std;
 
struct POINT {
    int x; int y;
    bool operator==(const POINT &other) {
        return (x == other.x && y == other.y);
    }
} ptBase;
 
typedef vector<POINT> PTARRAY;
 
bool CompareAngle(POINT pt1, POINT pt2) {
    pt1.x -= ptBase.x, pt1.y -= ptBase.y;
    pt2.x -= ptBase.x, pt2.y -= ptBase.y;
    return (pt1.x / sqrt((float)(pt1.x * pt1.x + pt1.y * pt1.y)) <
        pt2.x / sqrt((float)(pt2.x * pt2.x + pt2.y * pt2.y)));
}
 
void CalcConvexHull(PTARRAY &vecSrc, PTARRAY &vecCH) {
    ptBase = vecSrc.back();
    sort(vecSrc.begin(), vecSrc.end() - 1, &CompareAngle);
    vecCH.push_back(ptBase);
    vecCH.push_back(vecSrc.front());
    POINT ptLastVec = { vecCH.back().x - ptBase.x,
        vecCH.back().y - ptBase.y };
    PTARRAY::iterator i = vecSrc.begin();
    for (++i; i != vecSrc.end() - 1; ++i) {
        POINT ptCurVec = { i->x - vecCH.back().x, i->y - vecCH.back().y };
        while (ptCurVec.x * ptLastVec.y - ptCurVec.y * ptLastVec.x < 0) {
            vecCH.pop_back();
            ptCurVec.x = i->x - vecCH.back().x;
            ptCurVec.y = i->y - vecCH.back().y;
            ptLastVec.x = vecCH.back().x - (vecCH.end() - 2)->x;
            ptLastVec.y = vecCH.back().y - (vecCH.end() - 2)->y;
        }
        vecCH.push_back(*i);
        ptLastVec = ptCurVec;
    }
    vecCH.push_back(vecCH.front());
}
 
int CalcArea(PTARRAY &vecCH) {
    int nArea = 0;
    for (PTARRAY::iterator i = vecCH.begin(); i != vecCH.end() - 1; ++i) {
        nArea += (i + 1)->x * i->y - i->x * (i + 1)->y;
    }
    return nArea;
}
 
bool PointInConvexHull(POINT pt, PTARRAY &vecCH) {
    for (PTARRAY::iterator i = vecCH.begin(); i != vecCH.end() - 1; ++i) {
        int nX1 = pt.x - i->x, nY1 = pt.y - i->y;
        int nX2 = (i + 1)->x - i->x, nY2 = (i + 1)->y - i->y;
        if (nX1 * nY2 - nY1 * nX2 < 0) {
            return false;
        }
    }
    return true;
}
 
int main(void) {
    vector<PTARRAY> vecKingdom;
    POINT ptIn;
    int aFlag[100] = {0}, nAreaSum = 0;
    for (int nPtCnt; cin >> nPtCnt && nPtCnt >= 1;) {
        PTARRAY vecSrc, vecCH;
        cin >> ptIn.x >> ptIn.y;
        vecSrc.push_back(ptIn);
        for (; --nPtCnt != 0;) {
            cin >> ptIn.x >> ptIn.y;
            POINT &ptMin = vecSrc.back();
            vecSrc.insert(vecSrc.end() - (ptIn.y > ptMin.y ||
                (ptIn.y == ptMin.y && ptIn.x > ptMin.x)), ptIn);
        }
        CalcConvexHull(vecSrc, vecCH);
        vecKingdom.push_back(vecCH);
    }
    while (cin >> ptIn.x >> ptIn.y) {
        vector<PTARRAY>::iterator i = vecKingdom.begin();
        for (int k = 0; i != vecKingdom.end(); ++i, ++k) {
            if (PointInConvexHull(ptIn, *i) && aFlag[k] != 1) {
                nAreaSum += CalcArea(*i);
                aFlag[k] = 1;
                break;
            }
        }
    }
    cout << setiosflags(ios::fixed) << setprecision(2);
    cout << (float)nAreaSum / 2.0f << endl;
    return 0;
}

Problem Description

破解字迷之后,你得知Kid将会在展览开始后T分钟内盗取至少一颗宝石,并离开展馆。整个展馆呈矩形分布,划分为N*M个区域,有唯一的入口和出口(不能从出口进入,同样不能从入口出去)。由某个区域可直接移动至相邻四个区域中的一个,且最快需要一分钟。假设Kid进入放有宝石的区域即可盗取宝石,无需耗时。问至少要封锁几个区域(可以封锁放有宝石的区域,但不能封锁入口和出口)才能保证Kid无法完成任务。

Input

输入的第一行有一个整数C,代表有C组测试数据。每组测试数据的第一行有三个整数N,M,T(2<=N,M<=8,T>0)。接下来N行M列为展馆布置图,其中包括:

‘S’:入口
‘E’:出口
‘J’:放有宝石的区域,至少出现一次
‘.’:空白区域
‘#’:墙

Output
对每组测试数据,输出至少要封锁的区域数。

#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#define maxn 15
using namespace std;
 
int n,m,t,ans;
int sx,sy,ex,ey;
char mp[maxn][maxn];
char s[maxn];
bool vis[maxn][maxn][2];  // 三维判重 第三维-是否偷到珠宝
int dx[]={-1,1,0,0};
int dy[]={0,0,-1,1};
struct Node
{
    int x,y;
    int step,cnt;
    int pathx[65],pathy[65];  // 记录路径
};
queue<Node>q;
 
void dfs(int depth)
{
    if(depth>=ans) return ;   // 剪枝
    char c;
    int i,j,flag=0;
    int nx,ny,nstep,ncnt,tx,ty;
    Node cur,now;             // 这里不能用全局变量
    memset(vis,0,sizeof(vis));
    while(!q.empty()) q.pop();
    cur.x=sx;
    cur.y=sy;
    cur.cnt=0;
    cur.step=0;
    vis[sx][sy][0]=1;
    q.push(cur);
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        nx=now.x;
        ny=now.y;
        nstep=now.step;
        ncnt=now.cnt;
        if(nstep>t) break ;
        if(nx==ex&&ny==ey&&ncnt)  // 到达终点且偷到珠宝
        {
            flag=1;
            break ;
        }
        else if(nx==ex&&ny==ey) continue ;
        cur=now;
        for(i=0;i<4;i++)
        {
            tx=nx+dx[i];
            ty=ny+dy[i];
            cur.cnt=ncnt;
            if(mp[tx][ty]=='J') cur.cnt=1;
            if(mp[tx][ty]!='#'&&!vis[tx][ty][cur.cnt])
            {
                vis[tx][ty][cur.cnt]=1;
                cur.x=tx;
                cur.y=ty;
                cur.step=nstep+1;
                cur.pathx[cur.step]=tx;
                cur.pathy[cur.step]=ty;
                q.push(cur);
            }
        }
    }
    if(!flag)   // 如果能阻止盗贼偷到珠宝
    {
        if(ans>depth) ans=depth;  // 更新ans
        return ;
    }
    for(i=1;i<=nstep;i++)  // 不能的话需继续封锁 在盗贼可行路径上封锁
    {
        c=mp[now.pathx[i]][now.pathy[i]];
        if(c=='S'||c=='E') continue ;
        mp[now.pathx[i]][now.pathy[i]]='#';
        dfs(depth+1);
        mp[now.pathx[i]][now.pathy[i]]=c;  // 回溯
    }
}
int main()
{
    int i,j,test;
    scanf("%d",&test);
    while(test--)
    {
        scanf("%d%d%d",&n,&m,&t);
        memset(mp,'#',sizeof(mp));
        for(i=1;i<=n;i++)
        {
            scanf("%s",s);
            for(j=1;j<=m;j++)
            {
                mp[i][j]=s[j-1];
                if(s[j-1]=='S')
                {
                    sx=i;
                    sy=j;
                }
                else if(s[j-1]=='E')
                {
                    ex=i;
                    ey=j;
                }
            }
        }
        ans=4;
        dfs(0);  // 开始默认不需要封锁
        printf("%d\n",ans);
    }
    return 0;
}
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#define maxn 15
using namespace std;
 
int n,m,t,ans;
int sx,sy,ex,ey;
char mp[maxn][maxn];
char s[maxn];
bool vis[maxn][maxn][2];  // 三维判重 第三维-是否偷到珠宝
int dx[]={-1,1,0,0};
int dy[]={0,0,-1,1};
struct Node
{
    int x,y;
    int step,cnt;
    int pathx[65],pathy[65];  // 记录路径
};
queue<Node>q;
 
void dfs(int depth)
{
    if(depth>=ans) return ;   // 剪枝
    char c;
    int i,j,flag=0;
    int nx,ny,nstep,ncnt,tx,ty;
    Node cur,now;             // 这里不能用全局变量
    memset(vis,0,sizeof(vis));
    while(!q.empty()) q.pop();
    cur.x=sx;
    cur.y=sy;
    cur.cnt=0;
    cur.step=0;
    vis[sx][sy][0]=1;
    q.push(cur);
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        nx=now.x;
        ny=now.y;
        nstep=now.step;
        ncnt=now.cnt;
        if(nstep>t) break ;
        if(nx==ex&&ny==ey&&ncnt)  // 到达终点且偷到珠宝
        {
            flag=1;
            break ;
        }
        else if(nx==ex&&ny==ey) continue ;
        cur=now;
        for(i=0;i<4;i++)
        {
            tx=nx+dx[i];
            ty=ny+dy[i];
            cur.cnt=ncnt;
            if(mp[tx][ty]=='J') cur.cnt=1;
            if(mp[tx][ty]!='#'&&!vis[tx][ty][cur.cnt])
            {
                vis[tx][ty][cur.cnt]=1;
                cur.x=tx;
                cur.y=ty;
                cur.step=nstep+1;
                cur.pathx[cur.step]=tx;
                cur.pathy[cur.step]=ty;
                q.push(cur);
            }
        }
    }
    if(!flag)   // 如果能阻止盗贼偷到珠宝
    {
        if(ans>depth) ans=depth;  // 更新ans
        return ;
    }
    for(i=1;i<=nstep;i++)  // 不能的话需继续封锁 在盗贼可行路径上封锁
    {
        c=mp[now.pathx[i]][now.pathy[i]];
        if(c=='S'||c=='E') continue ;
        mp[now.pathx[i]][now.pathy[i]]='#';
        dfs(depth+1);
        mp[now.pathx[i]][now.pathy[i]]=c;  // 回溯
    }
}
int main()
{
    int i,j,test;
    scanf("%d",&test);
    while(test--)
    {
        scanf("%d%d%d",&n,&m,&t);
        memset(mp,'#',sizeof(mp));
        for(i=1;i<=n;i++)
        {
            scanf("%s",s);
            for(j=1;j<=m;j++)
            {
                mp[i][j]=s[j-1];
                if(s[j-1]=='S')
                {
                    sx=i;
                    sy=j;
                }
                else if(s[j-1]=='E')
                {
                    ex=i;
                    ey=j;
                }
            }
        }
        ans=4;
        dfs(0);  // 开始默认不需要封锁
        printf("%d\n",ans);
    }
    return 0;
}

Problem Description

在一无限大的二维平面中,我们做如下假设:
1、 每次只能移动一格;
2、 不能向后走(假设你的目的地是“向上”,那么你可以向左走,可以向右走,也可以向上走,但是不可以向下走);
3、 走过的格子立即塌陷无法再走第二次;

求走n步不同的方案数(2种走法只要有一步不一样,即被认为是不同的方案)。

Input

首先给出一个正整数C,表示有C组测试数据
接下来的C行,每行包含一个整数n (n<=20),表示要走n步。

Output

请编程输出走n步的不同方案总数;
每组的输出占一行。

#include<stdio.h>
int main()
{
    int a[25];
    a[0]=1;
    a[1]=3;
    for(int i=2;i<=20;i++)
    {
            a[i]=2*a[i-1]+a[i-2];
    }
    int n,t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        printf("%d\n",a[n]);
    }
}

Problem Description

Zty is a man that always full of enthusiasm. He wants to solve every kind of difficulty ACM problem in the world. And he has a habit that he does not like to solve
a problem that is easy than problem he had solved. Now yifenfei give him n difficulty problems, and tell him their relative time to solve it after solving the other one.
You should help zty to find a order of solving problems to solve more difficulty problem.
You may sure zty first solve the problem 0 by costing 0 minute. Zty always choose cost more or equal time’s problem to solve.
Input
The input contains multiple test cases.
Each test case include, first one integer n ( 2< n < 15).express the number of problem.
Than n lines, each line include n integer Tij ( 0<=Tij<10), the i’s row and j’s col integer Tij express after solving the problem i, will cost Tij minute to solve the problem j.
Output
For each test case output the maximum number of problem zty can solved.

#include<stdio.h>
#include<string.h>
#define max(a,b) (a>b?a:b)
int map[1010][1010],vis[1010];
int ans,n;
void dfs(int i,int len,int num)
{
 ans=max(ans,len);
 if(len==n)
  return;
 for(int j=0;j<n;j++)
 {
  if(!vis[j]&&j!=i)
  {
   if(map[i][j]>=num)
   {
    vis[j]=1;
    dfs(j,len+1,map[i][j]);
    vis[j]=0;
   }
  }
 }
}
int main()
{
 //int n;
 while(scanf("%d",&n)!=EOF)
 {
  int i,j;
  for(i=0;i<n;i++)
  {
   for(j=0;j<n;j++)
    scanf("%d",&map[i][j]);
  }
  memset(vis,0,sizeof(vis));
  vis[0]=1;
  ans=-1;
  for(i=1;i<n;i++)
  {
   vis[i]=1;
   dfs(i,2,map[0][i]);
   vis[i]=0;
  }
  printf("%d\n",ans);
 }
}

Problem Description

Dilworth is the world’s most prominent collector of Russian nested dolls: he literally has thousands of them! You know, the wooden hollow dolls of different sizes of which the smallest doll is contained in the second smallest, and this doll is in turn contained in the next one and so forth. One day he wonders if there is another way of nesting them so he will end up with fewer nested dolls? After all, that would make his collection even more magnificent! He unpacks each nested doll and measures the width and height of each contained doll. A doll with width w1 and height h1 will fit in another doll of width w2 and height h2 if and only if w1 < w2 and h1 < h2. Can you help him calculate the smallest number of nested dolls possible to assemble from his massive list of measurements?

Input

On the first line of input is a single positive integer 1 <= t <= 20 specifying the number of test cases to follow. Each test case begins with a positive integer 1 <= m <= 20000 on a line of itself telling the number of dolls in the test case. Next follow 2m positive integers w1, h1,w2, h2, . . . ,wm, hm, where wi is the width and hi is the height of doll number i. 1 <= wi, hi <= 10000 for all i.

Output

For each test case there should be one line of output containing the minimum number of nested dolls possible.

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
using namespace std;

const int maxn = 20000+10;
const int INF = 10000+10;

struct Node
{
    int w,h;
}node[maxn], dp[maxn];

bool cmp(Node a, Node b)
{
    if(a.w == b.w) return a.h < b.h;
    else return a.w > b.w;
}

int main()
{
    int T;
    int n;
    scanf("%d", &T);
    while(T--)
    {
        scanf("%d", &n);
        for(int i = 0; i < n; i++)
        {
            scanf("%d%d", &node[i].w, &node[i].h);
            dp[i].w = dp[i].h = INF; //假设初始化有 N 个可以嵌套的娃娃
        }
        sort(node, node+n, cmp);
//for(int i = 0; i < n; i++) printf("%d %d\n", node[i].w, node[i].h); printf("\n");

        for(int i = 0; i < n; i++)
        {
            int j = 0;
            while(dp[j].w <= node[i].w || dp[j].h <= node[i].h) j++;
            dp[j].w = node[i].w; //不断更新为当前情况
            dp[j].h = node[i].h;
        }

// for(int i = 0; i < n; i++) printf("%d %d\n", dp[i].w, dp[i].h); printf("\n");

        int ans = 0;
        for(int i = 0; i < n; i++)
            if(dp[i].h != INF) //看有几个嵌套过
                ans++;

        printf("%d\n", ans);
    }
    return 0;
}

Problem Description

Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.

  • Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
  • Teleporting: FJ can move from any point X to the point 2 × X in a single minute.

If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?

Input

Line 1: Two space-separated integers: N and K

Output
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.

#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
struct node {
    int x,step;
}temp, p;
bool vis[10000005];
int d[2] = {1,-1};
int bfs(int a, int b)
{
    memset(vis,false,sizeof(vis));
    queue<node> q;
    while (!q.empty())   q.pop();
    p.x = a;
    p.step = 0;
    q.push(p);
    vis[a] = true;
    while (q.size()) {
        p = q.front();
        q.pop();
        if(p.x == b)  return p.step;
        for(int i = 0; i < 3; i++) {
            if (i == 2)     temp.x = p.x * 2;
            else    temp.x = p.x + d[i];
            if (temp.x < 0 || vis[temp.x] || temp.x>100000)    continue;
            vis[temp.x] = true;
            temp.step = p.step + 1;
            q.push(temp);
        }
    }
    return -1;
}
int main()
{
    int n, k;
    while (scanf("%d %d", &n, &k) != EOF)
    {
        int ans = bfs(n,k);
        printf("%d\n", ans);
    }
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值