PAT甲级

 

 

 

                                             欢迎找茬                                                    

                                                       作者 渣渣侠

 

                             

 

 

1001 A+B Format (20)(20 分)

Calculate a + b and output the sum in standard format -- that is, thedigits must be separated into groups of three by commas (unless thereare less than four digits).

Input

Each input file contains one test case. Each case contains a pair ofintegers a and b where -1000000 <= a, b <= 1000000. The numbersare separated by a space.

Output

For each test case, you should output the sum of a and b in one line.The sum must be written in the standard format.

Sample Input

-1000000 9

Sample Output

-999,991

 

#include<bits/stdc++.h>
using namespace std;

int main(){
   int a, b, c;
   cin >> a >> b;
   c = a+b;
   if(c < 0) {  putchar('-'); c = -c;}
   string s = to_string(c);
   int len = s.length(), k = len/3, t = len-3*k;
   for(int i = 0; i < len; i++){
      cout << s[i];
      if( i != len-1 && (i-t+1)%3 == 0) cout<<',';
   }
   return 0;
}

 

 

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1002 A+B for Polynomials (25)(25 分)

This time, you are supposed to find A+B where A and B are twopolynomials.

Input

Each input file contains one test case. Each case occupies 2 lines, andeach line contains the information of a polynomial: K N1 a~N1~ N2 a~N2~... NK a~NK~, where K is the number of nonzero terms in the polynomial,Ni and a~Ni~ (i=1, 2, ..., K) are the exponents and coefficients,respectively. It is given that 1 <= K <= 10,0 <= NK < ...< N2 < N1 <=1000.

Output

For each test case you should output the sum of A and B in one line,with the same format as the input. Notice that there must be NO extraspace at the end of each line. Please be accurate to 1 decimal place.

Sample Input

2 1 2.4 0 3.2
2 2 1.5 1 0.5

Sample Output

3 2 1.5 1 2.9 0 3.2

 

#include<bits/stdc++.h>
using namespace std;

const int maxn = 1000+5;
double N[maxn];

int main(){
   int T = 2, n, k;
   double a;
   while(T--){
      cin >> n;
      while(n--){
         cin >> k >> a;
         N[k] += a;
      }
   }
   int cnt = 0;
   for(auto i : N)   if(i != 0.0) cnt++;
   cout<<cnt;
   for(int i = maxn-1; i >= 0; i--)
      if(N[i] != 0.0)
         printf(" %d %.1f",i,N[i]);
   return 0;
}

 

 

 

 

 

 

--------------------------------------------------------------------------------------------------------------

1003 Emergency (25)(25 分)

As an emergency rescue team leader of a city, you are given a specialmap of your country. The map shows several scattered cities connected bysome roads. Amount of rescue teams in each city and the length of eachroad between any pair of cities are marked on the map. When there is anemergency call to you from some other city, your job is to lead your mento the place as quickly as possible, and at the mean time, call up asmany hands on the way as possible.

Input

Each input file contains one test case. For each test case, the firstline contains 4 positive integers: N (<= 500) - the number of cities(and the cities are numbered from 0 to N-1), M - the number of roads, C1and C2 - the cities that you are currently in and that you must save,respectively. The next line contains N integers, where the i-th integeris the number of rescue teams in the i-th city. Then M lines follow,each describes a road with three integers c1, c2 and L, which are thepair of cities connected by a road and the length of that road,respectively. It is guaranteed that there exists at least one path fromC1 to C2.

Output

For each test case, print in one line two numbers: the number ofdifferent shortest paths between C1 and C2, and the maximum amount ofrescue teams you can possibly gather.\All the numbers in a line must be separated by exactly one space, andthere is no extra space allowed at the end of a line.

Sample Input

5 6 0 2
1 2 1 5 3
0 1 1
0 2 2
0 3 1
1 2 1
2 4 1
3 4 1

Sample Output

2 4

 

#include<bits/stdc++.h>
using namespace std;

const int maxn = 500+5, inf = 9999999;
int d[maxn][maxn];
int weight[maxn];
int dist[maxn];
int road[maxn];
int peo[maxn];
bool v[maxn];
int N, M, C1, C2;

int main(){
   cin >> N >> M >> C1 >> C2;
   for(int i = 0; i < N; i++) scanf("%d", &weight[i]);
   for(int i = 0; i < M; i++) {
      int a, b, c;
      scanf("%d%d%d", &a, &b, &c);
      d[b][a] = d[a][b] = c;
   }
   fill(dist, dist+maxn, inf);
   fill(v, v+maxn, false);
   dist[C1] = 0;
   peo[C1] = weight[C1];
   road[C1] = 1;
   for(int k = 0; k < N; k++){
      int u = -1, maxc = inf;
      for(int i = 0; i < N; i++){
         if(!v[i] && dist[i] < maxc) maxc = dist[u = i];
      }
      if(u == -1) break;
      v[u] = true;
      for(int i = 0; i < N; i++){
         int dis = d[u][i];
         if(v[i] || !dis) continue;
         if(dist[i] > dist[u] + dis){
            dist[i] = dist[u] + dis;
            peo[i] = peo[u] + weight[i];
            road[i] = road[u];
         }
         else if(dist[i] == dist[u] + dis){
            peo[i] = max(peo[i], weight[i] + peo[u]);
            road[i] += road[u];
         }
      }
   }
   cout<<road[C2]<<" "<<peo[C2]<<endl;
   return 0;
}

 

 

 

 

 

-----------------------------------------------------------------------------------------------------------------

1004 Counting Leaves (30)(30 分)

A family hierarchy is usually presented by a pedigree tree. Your job isto count those family members who have no child.

Input

Each input file contains one test case. Each case starts with a linecontaining 0 < N < 100, the number of nodes in a tree, and M (<N), the number of non-leaf nodes. Then M lines follow, each in theformat:

ID K ID[1] ID[2] ... ID[K]

where ID is a two-digit number representing a given non-leaf node, K isthe number of its children, followed by a sequence of two-digit ID's ofits children. For the sake of simplicity, let us fix the root ID to be01.

Output

For each test case, you are supposed to count those family members whohave no child for every seniority level starting from the root. Thenumbers must be printed in a line, separated by a space, and there mustbe no extra space at the end of each line.

The sample case represents a tree with only 2 nodes, where 01 is theroot and 02 is its only child. Hence on the root 01 level, there is 0leaf node; and on the next level, there is 1 leaf node. Then we shouldoutput "0 1" in a line.

Sample Input

2 1
01 1 02

Sample Output

0 1

 

 

 

#include<bits/stdc++.h>
using namespace std;

const int maxn = 100+5;
vector< vector<int> >v;
int N, M;

int main(){
   cin>> N >> M;
   v.resize(N+1);
   while(M--){
      int id, k, child;
      cin >> id >> k;
      while(k--){
         cin >> child;
         v[id].push_back(child);
      }
   }
   int k = 1, sum;
   queue<int>q;
   q.push(1);
   while(1){
      sum = 0;
      while(k--){
         int u = q.front();  q.pop();
         if(v[u].empty()) sum++;
         else for(auto it : v[u]) q.push(it);
      }
      cout<<sum;
      if(k = q.size()) cout<<" ";
      else break;
   }
   return 0;
}

 

 

 

 

 

 

----------------------------------------------------------------------------------------------------

1005 Spell It Right (20)(20 分)

Given a non-negative integer N, your task is to compute the sum of allthe digits of N, and output every digit of the sum in English.

Input Specification:

Each input file contains one test case. Each case occupies one linewhich contains an N (<= 10^100^).

Output Specification:

For each test case, output in one line the digits of the sum in Englishwords. There must be one space between two consecutive words, but noextra space at the end of a line.

 

Sample Input:

12345

Sample Output:

one 

 

#include<bits/stdc++.h>
using namespace std;

const char *t[10] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};

int main(){
   string s;
   int sum = 0;
   cin>>s;
   for(auto it:s) sum += (it - '0');
   if( !sum ) cout<<t[0]<<endl;
   else{
      string Sum = to_string(sum);
      for(int i = 0; i < Sum.length(); i++){
         if(i) cout<<" ";
         cout<<t[ Sum[i]-'0' ];
      }
   }
   return 0;
}

 

 

 

 

 

 

 

 

 

-------------------------------------------------------------------------------------------------------------

1006 Sign In and Sign Out (25)(25 分) 

At the beginning of every day, the first person who signs in thecomputer room will unlock the door, and the last one who signs out willlock the door. Given the records of signing in's and out's, you aresupposed to find the ones who have unlocked and locked the door on thatday.

Input Specification:

Each input file contains one test case. Each case contains the recordsfor one day. The case starts with a positive integer M, which is thetotal number of records, followed by M lines, each in the format:

ID_number Sign_in_time Sign_out_time

where times are given in the format HH:MM:SS, and ID number is a stringwith no more than 15 characters.

Output Specification:

For each test case, output in one line the ID numbers of the persons whohave unlocked and locked the door on that day. The two ID numbers mustbe separated by one space.

Note: It is guaranteed that the records are consistent. That is, thesign in time must be earlier than the sign out time for each person, andthere are no two persons sign in or out at the same moment.

Sample Input:

3
CS301111 15:30:28 17:00:10
SC3021234 08:00:00 11:25:25
CS301133 21:45:00 21:58:40

Sample Output:

SC3021234 CS301133

 

#include<bits/stdc++.h>
using namespace std;

string first, last;
int firsttime, lasttime;

int main(){
   int N;
   scanf("%d",&N);
   getchar();
   for(int i = 0; i < N; i++){
      string name;
      int h1, m1, s1, h2, m2, s2, t1, t2;
      cin>>name;
      scanf("%d:%d:%d %d:%d:%d",&h1,&m1,&s1,&h2,&m2,&s2);
      t1 = h1*3600 + m1*60 + s1;   t2 = h2*3600 + m2*60 + s2;
      if(!i || t1 < firsttime){ firsttime = t1; first = name;}
      if(!i || t2 > lasttime) { lasttime = t2; last = name;}
   }
   cout<<first<<" "<<last<<endl;
   return 0;
}

 

 

 

 

 

 

-----------------------------------------------------------------------------------------------------------------------------

1007 Maximum Subsequence Sum (25)(25 分)

Given a sequence of K integers { N~1~, N~2~, ..., N~K~ }. A continuoussubsequence is defined to be { N~i~, N~i+1~, ..., N~j~ } where 1 <= i<= j <= K. The Maximum Subsequence is the continuous subsequencewhich has the largest sum of its elements. For example, given sequence {-2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } withthe largest sum being 20.

Now you are supposed to find the largest sum, together with the firstand the last numbers of the maximum subsequence.

Input Specification:

Each input file contains one test case. Each case occupies two lines.The first line contains a positive integer K (<= 10000). The secondline contains K numbers, separated by a space.

Output Specification:

For each test case, output in one line the largest sum, together withthe first and the last numbers of the maximum subsequence. The numbersmust be separated by one space, but there must be no extra space at theend of a line. In case that the maximum subsequence is not unique,output the one with the smallest indices i and j (as shown by the samplecase). If all the K numbers are negative, then its maximum sum isdefined to be 0, and you are supposed to output the first and the lastnumbers of the whole sequence.

Sample Input:

10
-10 1 2 3 4 -5 -23 3 7 -21

Sample Output:

10 1 4

 

 

#include<bits/stdc++.h>
using namespace std;

const int inf = 9999999;
int N, a;
int maxsum, tempsum = 0, i, j, i1;
int Start, End;

int main(){
   maxsum = -inf;
   cin >> N;
   for(int k = 0; k < N; k++){
      scanf("%d",&a);
      if( !k )  Start = a; 
      if( k == N-1) End = a;
      if( !tempsum ) i1 = a;
      tempsum += a;
      if( tempsum > maxsum ){
         i = i1; j = a; maxsum = tempsum;
      }
      if( tempsum <= 0 ) tempsum = 0;
      
   }
   if(maxsum >= 0) cout<<maxsum<<" "<<i<<" "<<j<<endl;
   else cout<<"0 "<<Start<<" "<<End<<endl;
   return 0;
}

 

 

 

 

 

 

-----------------------------------------------------------------------------------------------------------------

1008 Elevator (20)(20 分)

The highest building in our city has only one elevator. A request listis made up with N positive numbers. The numbers denote at which floorsthe elevator will stop, in specified order. It costs 6 seconds to movethe elevator up one floor, and 4 seconds to move down one floor. Theelevator will stay for 5 seconds at each stop.

For a given request list, you are to compute the total time spent tofulfill the requests on the list. The elevator is on the 0th floor atthe beginning and does not have to return to the ground floor when therequests are fulfilled.

Input Specification:

Each input file contains one test case. Each case contains a positiveinteger N, followed by N positive numbers. All the numbers in the inputare less than 100.

Output Specification:

For each test case, print the total time on a single line.

Sample Input:

3 2 3 1

Sample Output:

41

 

#include<bits/stdc++.h>
using namespace std;

int main(){
   int N, sum, past = 0, cur;
   cin >> N;
   sum = 5*N;
   for(int i = 0; i < N; i++){
      cin >> cur;
      sum += ( (cur > past ? 6: 4)*abs(cur-past) );
      past = cur;
   }
   cout<<sum<<endl;
   return 0;
}

 

 

 

 

 

----------------------------------------------------------------------------------------------------------------------------

1009 Product of Polynomials (25)(25 分)

This time, you are supposed to find A*B where A and B are twopolynomials.

Input Specification:

Each input file contains one test case. Each case occupies 2 lines, andeach line contains the information of a polynomial: K N1 a~N1~ N2 a~N2~... NK a~NK~, where K is the number of nonzero terms in the polynomial,Ni and a~Ni~ (i=1, 2, ..., K) are the exponents and coefficients,respectively. It is given that 1 <= K <= 10, 0 <= NK < ...< N2 < N1 <=1000.

Output Specification:

For each test case you should output the product of A and B in one line,with the same format as the input. Notice that there must be NO extraspace at the end of each line. Please be accurate up to 1 decimal place.

Sample Input

2 1 2.4 0 3.2
2 2 1.5 1 0.5

Sample Output

3 3 3.6 2 6.0 1 1.6

 

#include<bits/stdc++.h>
using namespace std;

map<int, double> Map0, Map1;


int main(){
   int K, N;
   double a;
   cin >> K;
   while(K--){
      cin >> N >> a;
      Map0[N] = a;
   }
   cin >> K;
   while(K--){
      cin >> N >> a;
      for(auto it: Map0)  Map1[ it.first + N ] += (it.second * a);
   }
   int cnt = 0;
   for(auto it : Map1)
     if(it.second != 0.0) cnt++;
   cout << cnt;

   for(auto it = prev(Map1.end());; it--){
     if(it->second != 0.0)  printf(" %d %.1f",it->first,it->second);
     if(it == Map1.begin() ) break;
   }
   return 0;
}

 

 

 

 

 

----------------------------------------------------------------------------------------------------------------------

1010 Radix (25)(25 分)

Given a pair of positive integers, for example, 6 and 110, can thisequation 6 = 110 be true? The answer is "yes", if 6 is a decimal numberand 110 is a binary number.

Now for any pair of positive integers N1 and N2, your task is to findthe radix of one number while that of the other is given.

Input Specification:

Each input file contains one test case. Each case occupies a line whichcontains 4 positive integers:\N1 N2 tag radix\Here N1 and N2 each has no more than 10 digits. A digit is less than itsradix and is chosen from the set {0-9, a-z} where 0-9 represent thedecimal numbers 0-9, and a-z represent the decimal numbers 10-35. Thelast number "radix" is the radix of N1 if "tag" is 1, or of N2 if "tag"is 2.

Output Specification:

For each test case, print in one line the radix of the other number sothat the equation N1 = N2 is true. If the equation is impossible, print"Impossible". If the solution is not unique, output the smallestpossible radix.

Sample Input 1:

6 110 1 10

Sample Output 1:

2

Sample Input 2:

1 ab 1 2

Sample Output 2:

Impossible
#include<bits/stdc++.h>
using namespace std;

typedef long long int ll;

int main(){
   string a, b;
   int tag, radix;
   ll sum = 0, MinRadix = 2, MaxRadix, ans;
   cin>>a>>b>>tag>>radix;
   if(tag == 2) swap(a,b);
   for(int i = 0; i < a.length(); i++)  sum = sum*radix+( isdigit(a[i]) ? (a[i]-'0'):(a[i]-'a'+10) );
   for(int i = b.length()-1; i >= 0; i--)
      MinRadix = max(MinRadix, (ll)( isdigit(b[i]) ? (b[i]-'0'+1):(b[i]-'a'+11) )  );
   MaxRadix = sum+1; ans = sum+2;
   while(MinRadix <= MaxRadix){
      ll k = (MinRadix + MaxRadix)/2, Sum = 0;
      for(int i = 0; i < b.length(); i++){
         Sum = Sum*k+( isdigit(b[i] ) ? (b[i]-'0'):(b[i]-'a'+10) );
         if(Sum > sum || Sum < 0) break;
      }
      if(Sum == sum) { ans = min(k, ans); MaxRadix = k-1; }
      else if(Sum > sum || Sum < 0) MaxRadix = k-1;
      else MinRadix = k+1;
   }
   if(ans == sum+2) cout<<"Impossible\n";
   else cout<<ans<<endl;
   return 0;
}

 

 

 

 

 

----------------------------------------------------------------------------------------------------------------------

1011 World Cup Betting (20)(20 分)

With the 2010 FIFA World Cup running, football fans the world over werebecoming increasingly excited as the best players from the best teamsdoing battles for the World Cup trophy in South Africa. Similarly,football betting fans were putting their money where their mouths were,by laying all manner of World Cup bets.

Chinese Football Lottery provided a "Triple Winning" game. The rule ofwinning was simple: first select any three of the games. Then for eachselected game, bet on one of the three possible results -- namely W forwin, T for tie, and L for lose. There was an odd assigned to eachresult. The winner's odd would be the product of the three odds times65%.

For example, 3 games' odds are given as the following:

 W    T    L
1.1  2.5  1.7
1.2  3.0  1.6
4.1  1.2  1.1

To obtain the maximum profit, one must buy W for the 3rd game, T for the2nd game, and T for the 1st game. If each bet takes 2 yuans, then themaximum profit would be (4.1*3.0*2.5*65%-1)*2 = 37.98 yuans(accurate up to 2 decimal places).

Input

Each input file contains one test case. Each case contains the bettinginformation of 3 games. Each game occupies a line with three distinctodds corresponding to W, T and L.

Output

For each test case, print in one line the best bet of each game, and themaximum profit accurate up to 2 decimal places. The characters and thenumber must be separated by one space.

Sample Input

1.1 2.5 1.7
1.2 3.0 1.6
4.1 1.2 1.1

Sample Output

T T W 37.98

 

 

 

#include<bits/stdc++.h>
using namespace std;

int main(){
   int T = 3;
   double sum = 1, a, b, c;
   while(T--){
     cin >> a >> b >> c;
     if(a > b){
        if(a > c) {cout << "W "; sum *= a;}
        else      {cout << "L "; sum *= c;}
     }
     else{
        if(b > c) {cout << "T "; sum *= b;}
        else      {cout << "L "; sum *= c;} 
     }
   }
   printf("%.2f\n",(0.65*sum - 1)*2);
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------

1012 The Best Rank (25)(25 分)

To evaluate the performance of our first year CS majored students, weconsider their grades of three courses only: C - C Programming Language,M - Mathematics (Calculus or Linear Algebra), and E - English. At themean time, we encourage students by emphasizing on their best ranks --that is, among the four ranks with respect to the three courses and theaverage grade, we print the best rank for each student.

For example, The grades of C, M, E and A - Average of 4 students aregiven as the following:

StudentID  C  M  E  A
310101     98 85 88 90
310102     70 95 88 84
310103     82 87 94 88
310104     91 91 91 91

Then the best ranks for all the students are No.1 since the 1st onehas done the best in C Programming Language, while the 2nd one inMathematics, the 3rd one in English, and the last one in average.

Input

Each input file contains one test case. Each case starts with a linecontaining 2 numbers N and M (<=2000), which are the total number ofstudents, and the number of students who would check their ranks,respectively. Then N lines follow, each contains a student ID which is astring of 6 digits, followed by the three integer grades (in the rangeof [0, 100]) of that student in the order of C, M and E. Then thereare M lines, each containing a student ID.

Output

For each of the M students, print in one line the best rank for him/her,and the symbol of the corresponding rank, separated by a space.

The priorities of the ranking methods are ordered as A > C > M> E. Hence if there are two or more ways for a student to obtain thesame best rank, output the one with the highest priority.

If a student is not on the grading list, simply output "N/A".

Sample Input

5 6
310101 98 85 88
310102 70 95 88
310103 82 87 94
310104 91 91 91
310105 85 90 90
310101
310102
310103
310104
310105
999999

Sample Output

1 C
1 M
1 E
1 A
3 A
N/A

 

 

 

#include<bits/stdc++.h>
using namespace std;

const int maxn = 2000+10;
const char *Course = "ACME";
int N, M, k;
struct node{
  int id;
  int grade[4], rank[4];
  int bestrank;
  char course;
}stu[maxn];

map<int, string> IDcache;

bool cmp(node a, node b){
   return a.grade[k] > b.grade[k];
}

int main(){
   cin >> N >> M;
   for(int i = 0; i < N; i++){
      scanf("%d%d%d%d", &stu[i].id, &stu[i].grade[1], &stu[i].grade[2], &stu[i].grade[3]);
      stu[i].grade[0] = stu[i].grade[1] + stu[i].grade[2] + stu[i].grade[3];
      stu[i].bestrank = maxn;
   }

   for(k = 0; k < 4; k++){
      sort(stu, stu+N, cmp);
      for(int i = 0; i < N; i++){
         if(!i) stu[0].rank[k] = 1;
         else{
            if(stu[i].grade[k] == stu[i-1].grade[k]) stu[i].rank[k] = stu[i-1].rank[k];
            else stu[i].rank[k] = i+1;
         }
         if(stu[i].bestrank > stu[i].rank[k]){
             stu[i].bestrank = stu[i].rank[k];
             stu[i].course = Course[k];
         }
      }
   }

   for(int i = 0; i < N; i++)  IDcache[stu[i].id] = (to_string(stu[i].bestrank) + ' ' + stu[i].course);

   int id;
   for(int i = 0; i < M; i++){
      cin >> id;
      if(!IDcache.count(id) ) cout<<"N/A\n";
      else cout<<IDcache[id]<<endl;
   }
   return 0;
}

 

 

 

 

 

 

 

-------------------------------------------------------------------------------------------------------------------

1013 Battle Over Cities (25)(25 分)

It is vitally important to have all the cities connected by highways ina war. If a city is occupied by the enemy, all the highways from/towardthat city are closed. We must know immediately if we need to repair anyother highways to keep the rest of the cities connected. Given the mapof cities which have all the remaining highways marked, you are supposedto tell the number of highways need to be repaired, quickly.

For example, if we have 3 cities and 2 highways connectingcity~1~-city~2~ and city~1~-city~3~. Then if city~1~ is occupied by theenemy, we must have 1 highway repaired, that is the highwaycity~2~-city~3~.

Input

Each input file contains one test case. Each case starts with a linecontaining 3 numbers N (&lt1000), M and K, which are the total number ofcities, the number of remaining highways, and the number of cities to bechecked, respectively. Then M lines follow, each describes a highway by2 integers, which are the numbers of the cities the highway connects.The cities are numbered from 1 to N. Finally there is a line containingK numbers, which represent the cities we concern.

Output

For each of the K cities, output in a line the number of highways needto be repaired if that city is lost.

Sample Input

3 2 3
1 2
1 3
1 2 3

Sample Output

1
0
0

 

 

 

#include<bits/stdc++.h>
using namespace std;

const int maxn = 1000+10;
int N, M, K;
vector<vector<int> >v;
bool visit[maxn];

void dfs(int i){
  visit[i] = true;
   for(int &j : v[i]) if(!visit[j]) 
      dfs( j );
}

int main(){
   cin >> N >> M >> K;
   v.resize(N+1);
   for(int i = 0; i < M; i++){
       int a, b;
       scanf("%d%d",&a, &b);
       v[a].push_back(b);  v[b].push_back(a);
   }

   while(K--){
      memset(visit, false, sizeof(visit));
      int cnt = 0, c;
      cin >> c;
      visit[c] = true;
      for(int i = 1; i <= N; i++) if(!visit[i]) {
          dfs( i ); cnt++;
      }
      cout << cnt-1 << endl;
   }
   return 0;
}

 

 

 

 

 

-------------------------------------------------------------------------------------------------------------------

1014 Waiting in Line (30)(30 分)

Suppose a bank has N windows open for service. There is a yellow line infront of the windows which devides the waiting area into two parts. Therules for the customers to wait in line are:

  • The space inside the yellow line in front of each window is enoughto contain a line with M customers. Hence when all the N lines arefull, all the customers after (and including) the (NM+1)st one willhave to wait in a line behind the yellow line.
  • Each customer will choose the shortest line to wait in when crossingthe yellow line. If there are two or more lines with the samelength, the customer will always choose the window with thesmallest number.
  • Customer[i] will take T[i] minutes to have his/hertransaction processed.
  • The first N customers are assumed to be served at 8:00am.

Now given the processing time of each customer, you are supposed to tellthe exact time at which a customer has his/her business done.

For example, suppose that a bank has 2 windows and each window may have2 customers waiting inside the yellow line. There are 5 customerswaiting with transactions taking 1, 2, 6, 4 and 3 minutes, respectively.At 08:00 in the morning, customer~1~ is served at window~1~ whilecustomer~2~ is served at window~2~. Customer~3~ will wait in front ofwindow~1~ and customer~4~ will wait in front of window~2~. Customer~5~will wait behind the yellow line.

At 08:01, customer~1~ is done and customer~5~ enters the line in frontof window~1~ since that line seems shorter now. Customer~2~ will leaveat 08:02, customer~4~ at 08:06, customer~3~ at 08:07, and finallycustomer~5~ at 08:10.

Input

Each input file contains one test case. Each case starts with a linecontaining 4 positive integers: N (<=20, number of windows), M(<=10, the maximum capacity of each line inside the yellow line), K(<=1000, number of customers), and Q (<=1000, number of customerqueries).

The next line contains K positive integers, which are the processingtime of the K customers.

The last line contains Q positive integers, which represent thecustomers who are asking about the time they can have their transactionsdone. The customers are numbered from 1 to K.

Output

For each of the Q customers, print in one line the time at which his/hertransaction is finished, in the format HH:MM where HH is in [08, 17]and MM is in [00, 59]. Note that since the bank is closed everydayafter 17:00, for those customers who cannot be served before 17:00, youmust output "Sorry" instead.

Sample Input

2 2 7 5
1 2 6 4 3 534 2
3 4 5 6 7

Sample Output

08:07
08:06
08:10
17:00
Sorry
#include <bits/stdc++.h>
using namespace std;

const int maxc = 20+5, maxn = 1000+10, inf = 999999;
int N, M, K, Q, k;
int servetime[maxn], leveltime[maxn];
struct node{
   int id, first_end_time;
   bool operator < (const node &rhs) const {
      return first_end_time == rhs.first_end_time ? (id > rhs.id) : (first_end_time > rhs.first_end_time);
   }
};

priority_queue< node > window_Q;
queue< int >Win[maxc];

void init(){
   cin >> N >> M >> K >> Q;
   for(int i = 1; i <= K; i++){
       scanf("%d", &servetime[i]);
       leveltime[i] = inf;
   }
   for(k = 1; k <= K && k <= N*M; k++)
       Win[ (k % N) == 0 ? N: ( k%N ) ].push( k );
   for(int i = 1; i <= N; i++) if( !Win[i].empty() )
       window_Q.push( node{i, servetime[ Win[i].front() ] } );
}

void simulation(){
   while( !window_Q.empty() ){
      node u = window_Q.top();
      window_Q.pop();
      int a = Win[u.id].front();
      Win[u.id].pop();
      leveltime[a] = u.first_end_time;
      if(k <= K)   Win[u.id].push( k++ );
      if( !Win[u.id].empty() ){
          u.first_end_time += servetime[Win[u.id].front() ];
          window_Q.push( u );
      }
   }
}

int main(){
  init();
  simulation();
  while(Q--){
     int a;
     scanf("%d", &a);
     if(leveltime[a]-servetime[a] >= 540) cout<<"Sorry\n";
     else printf("%02d:%02d\n", leveltime[a]/60+8, leveltime[a]%60);
  }
  return 0;
}

 

 

 

 

 

 

-----------------------------------------------------------------------------------------------------------------

1015 Reversible Primes (20)(20 分)

A reversible prime in any number system is a prime whose "reverse" in that number system is also a prime. For example in the decimal system 73 is a reversible prime because its reverse 37 is also a prime.

Now given any two positive integers N (< 10^5^) and D (1 < D <= 10), you are supposed to tell if N is a reversible prime with radix D.

Input Specification:

The input file consists of several test cases. Each case occupies a line which contains two integers N and D. The input is finished by a negative N.

Output Specification:

For each test case, print in one line "Yes" if N is a reversible prime with radix D, or "No" if not.

Sample Input:

73 10
23 2
23 10
-2

Sample Output:

Yes
Yes
No

 

 

#include<bits/stdc++.h>
using namespace std;

bool isprime(int n){
   if(n == 1) return false;
   for(int i = 2; i*i <= n; i++){
      if(n % i == 0) return false;
   }
   return true;
}

int f(int N, int D){
   string s;
   int sum = 0;
   while(N > 0){
      s += (N%D+'0');
      N /= D;
   }
   for(auto it : s){
      sum = sum*D + (it-'0');
   }
   return sum;
}

int main(){
   int N, D;
   while( scanf("%d", &N) && N > 0 && scanf("%d", &D) ){
      if(isprime(N) && isprime( f(N,D) ) ) cout<<"Yes\n";
      else cout<<"No\n";
   }
  
   return 0;
}

 

 

 

 

 

 

------------------------------------------------------------------------------------------------------------------------------------------------------------

1016 Phone Bills (25)(25 分)

A long-distance telephone company charges its customers by the following rules:

Making a long-distance call costs a certain amount per minute, depending on the time of day when the call is made. When a customer starts connecting a long-distance call, the time will be recorded, and so will be the time when the customer hangs up the phone. Every calendar month, a bill is sent to the customer for each minute called (at a rate determined by the time of day). Your job is to prepare the bills for each month, given a set of phone call records.

Input Specification:

Each input file contains one test case. Each case has two parts: the rate structure, and the phone call records.

The rate structure consists of a line with 24 non-negative integers denoting the toll (cents/minute) from 00:00 - 01:00, the toll from 01:00

  • 02:00, and so on for each hour in the day.

The next line contains a positive number N (<= 1000), followed by N lines of records. Each phone call record consists of the name of the customer (string of up to 20 characters without space), the time and date (mm:dd:hh:mm), and the word "on-line" or "off-line".

For each test case, all dates will be within a single month. Each "on-line" record is paired with the chronologically next record for the same customer provided it is an "off-line" record. Any "on-line" records that are not paired with an "off-line" record are ignored, as are "off-line" records not paired with an "on-line" record. It is guaranteed that at least one call is well paired in the input. You may assume that no two records for the same customer have the same time. Times are recorded using a 24-hour clock.

Output Specification:

For each test case, you must print a phone bill for each customer.

Bills must be printed in alphabetical order of customers' names. For each customer, first print in a line the name of the customer and the month of the bill in the format shown by the sample. Then for each time period of a call, print in one line the beginning and ending time and date (dd:hh:mm), the lasting time (in minute) and the charge of the call. The calls must be listed in chronological order. Finally, print the total charge for the month in the format shown by the sample.

Sample Input:

10 10 10 10 10 10 20 20 20 15 15 15 15 15 15 15 20 30 20 15 15 10 10 10
10
CYLL 01:01:06:01 on-line
CYLL 01:28:16:05 off-line
CYJJ 01:01:07:00 off-line
CYLL 01:01:08:03 off-line
CYJJ 01:01:05:59 on-line
aaa 01:01:01:03 on-line
aaa 01:02:00:01 on-line
CYLL 01:28:15:41 on-line
aaa 01:05:02:24 on-line
aaa 01:04:23:59 off-line

Sample Output:

CYJJ 01
01:05:59 01:07:00 61 $12.10
Total amount: $12.10
CYLL 01
01:06:01 01:08:03 122 $24.40
28:15:41 28:16:05 24 $3.85
Total amount: $28.25
aaa 01
02:00:01 04:23:59 4318 $638.80
Total amount: $638.80

 

#include<bits/stdc++.h>
using namespace std;

const int maxn = 1000+10;
int rate[25];
char Status[25];
int N, month;
struct node{
   string name;
   int t[3], Time, status, money;
   bool operator < (const node &rhs) const{
      return ( name == rhs.name )? (Time < rhs.Time): (name < rhs.name) ;
   }
}Record[maxn];


int f(int dd, int hh, int mm){
   int sum = dd*rate[24]*60;
   if(hh)  sum += rate[hh]*60;
   sum += (rate[hh+1]-rate[hh])*mm;
   return sum;
}

int main(){
   for(int i = 1; i <= 24; i++){
      cin >> rate[i];
      rate[i] += rate[i-1];
   }

   cin >> N;
   for(int i = 0; i < N; i++){
      cin >> Record[i].name;
      scanf("%d:%d:%d:%d%s",&month, &Record[i].t[0], &Record[i].t[1], &Record[i].t[2], Status);
      Record[i].status = ( Status[1] == 'n');
      Record[i].Time = Record[i].t[0]*24*60 +Record[i].t[1]*60 + Record[i].t[2];
      Record[i].money = f(Record[i].t[0], Record[i].t[1], Record[i].t[2]);
   }
   sort(Record, Record+N);
   map<string, vector<node> > Map;
   for(int i = 0; i < N-1; i++){
      if(Record[i].name != Record[i+1].name || !Record[i].status || Record[i+1].status ) continue;
      Map[ Record[i].name ].push_back(Record[i]);
      Map[ Record[i].name ].push_back(Record[i+1]);
   }


   for(auto &it: Map){
      vector<node> &v = it.second;
      cout<<v[0].name;
      printf(" %02d\n",month);
      double sum = 0.0;
      for (int i = 0; i < v.size()-1; i += 2) {
         printf("%02d:%02d:%02d %02d:%02d:%02d %d $%.2f\n",v[i].t[0], v[i].t[1], v[i].t[2], v[i+1].t[0], v[i+1].t[1], v[i+1].t[2], v[i+1].Time-v[i].Time, (v[i+1].money-v[i].money)/100.0);
         sum += (v[i+1].money-v[i].money)/100.0;
      }
      printf("Total amount: $%.2f\n",sum);
   }
   return 0;
}

 

 

 

 

 

 

-----------------------------------------------------------------------------------------------------------------------------------------------------------------

1017 Queueing at Bank (25)(25 分)

Suppose a bank has K windows open for service. There is a yellow line in front of the windows which devides the waiting area into two parts. All the customers have to wait in line behind the yellow line, until it is his/her turn to be served and there is a window available. It is assumed that no window can be occupied by a single customer for more than 1 hour.

Now given the arriving time T and the processing time P of each customer, you are supposed to tell the average waiting time of all the customers.

Input Specification:

Each input file contains one test case. For each case, the first line contains 2 numbers: N (<=10000) - the total number of customers, and K (<=100) - the number of windows. Then N lines follow, each contains 2 times: HH:MM:SS - the arriving time, and P - the processing time in minutes of a customer. Here HH is in the range [00, 23], MM and SS are both in [00, 59]. It is assumed that no two customers arrives at the same time.

Notice that the bank opens from 08:00 to 17:00. Anyone arrives early will have to wait in line till 08:00, and anyone comes too late (at or after 17:00:01) will not be served nor counted into the average.

Output Specification:

For each test case, print in one line the average waiting time of all the customers, in minutes and accurate up to 1 decimal place.

Sample Input:

7 3
07:55:00 16
17:00:01 2
07:59:59 15
08:01:00 60
08:00:00 30
08:00:02 2
08:03:00 10

Sample Output:

8.2

 

#include<bits/stdc++.h>
using namespace std;

const int maxn = 10000+5;
int N, K, i = 0;
double wait = 0.0;
priority_queue<int, vector<int>, greater<int> >q;
struct node{
   int t[3], Time, P;
   bool operator < (const node &rhs) const {
      return Time < rhs.Time;
   }
}v[maxn];

int main(){
   cin >> N >> K;
   while(K--){ q.push(8*60*60); }
   while(N--){
      scanf("%d:%d:%d %d", &v[i].t[0], &v[i].t[1], &v[i].t[2], &v[i].P);
      v[i].Time = v[i].t[0]*60*60 + v[i].t[1]*60 + v[i].t[2];
      if(v[i].Time < 17*60*60+1) i++;
   }
   if(!i) {cout<<"0.0\n"; return 0;}
   sort(v, v+i);
   for(int j = 0; j < i; j++){
      int t = q.top(); q.pop();
      if(t > v[j].Time){
         wait += t-v[j].Time;
      }
      q.push( max(v[j].Time, t)+v[j].P*60 );
   }
   printf("%0.1f\n",wait/60.0/i );
   return 0;
}

 

 

 

 

 

 

------------------------------------------------------------------------------------------------------------------------------------------------------------------

1018 Public Bike Management (30)(30 分)

There is a public bike service in Hangzhou City which provides great convenience to the tourists from all over the world. One may rent a bike at any station and return it to any other stations in the city.

The Public Bike Management Center (PBMC) keeps monitoring the real-time capacity of all the stations. A station is said to be in perfect condition if it is exactly half-full. If a station is full or empty, PBMC will collect or send bikes to adjust the condition of that station to perfect. And more, all the stations on the way will be adjusted as well.

When a problem station is reported, PBMC will always choose the shortest path to reach that station. If there are more than one shortest path, the one that requires the least number of bikes sent from PBMC will be chosen.

\ Figure 1

Figure 1 illustrates an example. The stations are represented by vertices and the roads correspond to the edges. The number on an edge is the time taken to reach one end station from another. The number written inside a vertex S is the current number of bikes stored at S. Given that the maximum capacity of each station is 10. To solve the problem at S~3~, we have 2 different shortest paths:

1. PBMC -> S~1~ -> S~3~. In this case, 4 bikes must be sent from PBMC, because we can collect 1 bike from S~1~ and then take 5 bikes to S~3~, so that both stations will be in perfect conditions.

2. PBMC -> S~2~ -> S~3~. This path requires the same time as path 1, but only 3 bikes sent from PBMC and hence is the one that will be chosen.

Input Specification:

Each input file contains one test case. For each case, the first line contains 4 numbers: C~max~ (<= 100), always an even number, is the maximum capacity of each station; N (<= 500), the total number of stations; S~p~, the index of the problem station (the stations are numbered from 1 to N, and PBMC is represented by the vertex 0); and M, the number of roads. The second line contains N non-negative numbers C~i~ (i=1,...N) where each C~i~ is the current number of bikes at S~i~ respectively. Then M lines follow, each contains 3 numbers: S~i~, S~j~, and T~ij~ which describe the time T~ij~ taken to move betwen stations S~i~ and S~j~. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print your results in one line. First output the number of bikes that PBMC must send. Then after one space, output the path in the format: 0-&gtS~1~->...-&gtS~p~. Finally after another space, output the number of bikes that we must take back to PBMC after the condition of S~p~ is adjusted to perfect.

Note that if such a path is not unique, output the one that requires minimum number of bikes that we must take back to PBMC. The judge's data guarantee that such a path is unique.

Sample Input:

10 3 3 5
6 7 0
0 1 1
0 2 1
0 3 3
1 3 1
2 3 1

Sample Output:

3 0->2->3 0

 

#include<bits/stdc++.h>
using namespace std;


const int maxn = 500+5, inf = 999999;
int d[maxn][maxn], w[maxn], v[maxn], dis[maxn];
vector< vector< int > > path, p;
vector<int> temp, ans;
int Cmax, N, S, M, perfect, bestneed = inf, bestleft = inf;

void init(){
   cin >> Cmax >> N >> S >> M;
   perfect = Cmax/2;
   path.resize(N+1);
   p.resize(N+1);
   for(int i = 1; i <= N; i++) scanf("%d", &w[i]);
   while(M--){
      int a, b, c;
      scanf("%d%d%d", &a, &b, &c);
      d[b][a] = d[a][b] = c;
   }
}

void Dijkstra(){
   for(int i = 1; i <= N; i++) dis[i] = inf;
   for(int i = 0; i <= N; i++){
      int x = -1, m = inf;
      for(int y = 0; y <= N; y++) if(!v[y] && dis[y] < m) m = dis[ x = y ];
      if(x == -1) break;
      v[x] = 1;
      for(int y = 0; y <= N; y++) if(!v[y] && d[x][y]){
         if(dis[y] > dis[x] + d[x][y]){
            dis[y] = dis[x] + d[x][y];
            path[y].clear();
            path[y].push_back(x);
         }
         else if(dis[y] == dis[x] + d[x][y])
            path[y].push_back(x);
      }
   }
}

void getroad(){
	for(int i = 0; i <= N; i++)
		for(int j = 0; j < path[i].size(); j++)
			p[ path[i][j] ].push_back(i);
}

void dfs(int i, int Need, int Left){
   temp.push_back(i);
   int Size = p[i].size();
   if( i ){
      if( w[i] < perfect ){
   	     if( Left >= perfect-w[i] )	 Left -= perfect-w[i];
   	     else {
   	  	    Need += perfect-w[i]-Left;
   	  	    Left = 0;
   	     }
      } 
      else Left += w[i]-perfect;
   }
   if( i == S && ( ans.empty() ||  Need < bestneed || ( Need == bestneed && Left < bestleft ) ) ){
       ans = temp;
       bestneed = Need;
	   bestleft = Left;
   }
   else for(int j = 0; j < Size; j++){
       int k = p[i][j];
       dfs(k, Need, Left);
       temp.pop_back();
   }
}

void print(){
   cout<< bestneed <<' ';
   for(int i = 0; i < ans.size(); i++){
        if(i) cout << "->";
		cout << ans[i];
   }
   cout << " " << bestleft << endl;
}

int main(){
   init();
   Dijkstra();
   getroad();
   dfs(0, 0, 0);
   print();
   return 0;
}

 

 

 

 

 

 

-----------------------------------------------------------------------------------------------------------------------------------------------------------

1019 General Palindromic Number (20)(20 分)

A number that will be the same when it is written forwards or backwards is known as a Palindromic Number. For example, 1234321 is a palindromic number. All single digit numbers are palindromic numbers.

Although palindromic numbers are most often considered in the decimal system, the concept of palindromicity can be applied to the natural numbers in any numeral system. Consider a number N > 0 in base b >= 2, where it is written in standard notation with k+1 digits a~i~ as the sum of (a~i~b^i^) for i from 0 to k. Here, as usual, 0 <= a~i~ < b for all i and a~k~ is non-zero. Then N is palindromic if and only if a~i~ = a~k-i~ for all i. Zero is written 0 in any base and is also palindromic by definition.

Given any non-negative decimal integer N and a base b, you are supposed to tell if N is a palindromic number in base b.

Input Specification:

Each input file contains one test case. Each case consists of two non-negative numbers N and b, where 0 <= N <= 10^9^ is the decimal number and 2 <= b <= 10^9^ is the base. The numbers are separated by a space.

Output Specification:

For each test case, first print in one line "Yes" if N is a palindromic number in base b, or "No" if not. Then in the next line, print N as the number in base b in the form "a~k~ a~k-1~ ... a~0~". Notice that there must be no extra space at the end of output.

Sample Input 1:

27 2

Sample Output 1:

Yes
1 1 0 1 1

Sample Input 2:

121 5

Sample Output 2:

No
4 4 1

 

#include<bits/stdc++.h>
using namespace std;
const int maxn = 10000000;
int N, b, i = 0;
int s[maxn];

int main(){
   cin >> N >> b;
   if(!N)  cout<<"Yes\n0";
   else {
      while(N > 0){
         s[i++] = N % b;
         N /= b;
      }
      bool flag = true;
      for(int j = 0; j < i/2; j++){
         if(s[j] != s[i-j-1]){
            flag = false;
            break;
         }
      }
      if(flag) cout<<"Yes\n";
      else cout<<"No\n";
      for(int j = i-1; j >= 0; j--){
         cout<<s[j];
         if(j) cout<<" ";
      }
   }
   return 0;
}

 

 

 

 

------------------------------------------------------------------------------------------------------------------------------------------------------------

1020 Tree Traversals (25)(25 分)

Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:

7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

Sample Output:

4 1 6 3 5 7 2

 

#include<bits/stdc++.h>
using namespace std;
int N;
vector<int>post, in;
vector<vector<int> >level;

void levelorder(int postr, int inl, int inr, int h){
   if(inl > inr) return ;
   int i = inl;
   while(in[i] != post[postr]) i++;
   level[h].push_back( in[i] );
   levelorder(i-inr+postr-1, inl, i-1, h+1);
   levelorder(postr-1, i+1, inr, h+1);
}

void print(){
   for(int h = 0;; h++){
      for(int i = 0; i < level[h].size(); i++){
         cout<<level[h][i];
         if(--N) cout<<" ";
         else return;
      }
   }
}

int main(){
   cin >> N;
   post.resize(N), in.resize(N), level.resize(N);
   for(int i = 0; i < N; i++) cin >> post[i];
   for(int i = 0; i < N; i++) cin >> in[i];
   levelorder(N-1, 0, N-1, 0);
   print();
   return 0;
}

 

 

 

 

----------------------------------------------------------------------------------------------------------------------------------------------------------

1021 Deepest Root (25)(25 分)

A graph which is connected and acyclic can be considered a tree. The height of the tree depends on the selected root. Now you are supposed to find the root that results in a highest tree. Such a root is called the deepest root.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (<=10000) which is the number of nodes, and hence the nodes are numbered from 1 to N. Then N-1 lines follow, each describes an edge by given the two adjacent nodes' numbers.

Output Specification:

For each test case, print each of the deepest roots in a line. If such a root is not unique, print them in increasing order of their numbers. In case that the given graph is not a tree, print "Error: K components" where K is the number of connected components in the graph.

Sample Input 1:

5
1 2
1 3
1 4
2 5

Sample Output 1:

3
4
5

Sample Input 2:

5
1 3
1 4
2 5
3 4

Sample Output 2:

Error: 2 components

 

#include<bits/stdc++.h>
using namespace std;
const int maxn = 10000+5;
int N, maxdeep = -1, cnt = 0;
bool c[maxn];
vector<vector<int> >v;
set <int> Set;
vector<int>temp;

void dfs(int i, int deep){
   c[i] = true;
   for(int j = 0; j < v[i].size(); j++) if( !c[ v[i][j] ]  ){
      if(deep > maxdeep) {
        temp.clear();
        temp.push_back(v[i][j]);
        maxdeep = deep;
      }
      else if(deep == maxdeep) temp.push_back(v[i][j]);
      dfs(v[i][j], deep+1);
   }
   return;
}

int main(){
   cin >> N;
   v.reserve(N+1);
   for(int i = 0; i < N-1; i++){
      int a, b;
      scanf("%d%d",&a, &b);
      v[b].push_back(a); v[a].push_back(b);
   }
   for(int i = 1; i <= N; i++) if( !c[i] ) {
      cnt++;
      dfs(i, 0);
   }
   if(cnt > 1) cout<<"Error: "<<cnt<<" components\n";
   else if(N == 1) cout<<"1\n";
   else {
      maxdeep = -1;
      fill(c, c+maxn, false);
      for(auto i: temp) Set.insert(i);
      if(!temp.empty()) dfs(temp[0], 0);
      for(auto i: temp) Set.insert(i);
      for(auto &i : Set) cout<<i<<endl;
   }
   return 0;
}

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------------------------------------------

1022 Digital Library (30)(30 分)

A Digital Library contains millions of books, stored according to their titles, authors, key words of their abstracts, publishers, and published years. Each book is assigned an unique 7-digit number as its ID. Given any query from a reader, you are supposed to output the resulting books, sorted in increasing order of their ID's.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (<=10000) which is the total number of books. Then N blocks follow, each contains the information of a book in 6 lines:

  • Line #1: the 7-digit ID number;
  • Line #2: the book title -- a string of no more than 80 characters;
  • Line #3: the author -- a string of no more than 80 characters;
  • Line #4: the key words -- each word is a string of no more than 10 characters without any white space, and the keywords are separated by exactly one space;
  • Line #5: the publisher -- a string of no more than 80 characters;
  • Line #6: the published year -- a 4-digit number which is in the range [1000, 3000].

It is assumed that each book belongs to one author only, and contains no more than 5 key words; there are no more than 1000 distinct key words in total; and there are no more than 1000 distinct publishers.

After the book information, there is a line containing a positive integer M (<=1000) which is the number of user's search queries. Then M lines follow, each in one of the formats shown below:

  • 1: a book title
  • 2: name of an author
  • 3: a key word
  • 4: name of a publisher
  • 5: a 4-digit number representing the year

Output Specification:

For each query, first print the original query in a line, then output the resulting book ID's in increasing order, each occupying a line. If no book is found, print "Not Found" instead.

Sample Input:

3
1111111
The Testing Book
Yue Chen
test code debug sort keywords
ZUCS Print
2011
3333333
Another Testing Book
Yue Chen
test code sort keywords
ZUCS Print2
2012
2222222
The Testing Book
CYLL
keywords debug book
ZUCS Print2
2011
6
1: The Testing Book
2: Yue Chen
3: keywords
4: ZUCS Print
5: 2011
3: blablabla

Sample Output:

1: The Testing Book
1111111
2222222
2: Yue Chen
1111111
3333333
3: keywords
1111111
2222222
3333333
4: ZUCS Print
1111111
5: 2011
1111111
2222222
3: blablabla
Not Found

 

 

#include<bits/stdc++.h>
using namespace std;

const int maxn = 1000+5;
int N, M;
map<string, set<int> > Map[6];

int main(){
  string s;
  cin >> N;
  while(N--){
     int id;
     scanf("%d\n",&id);
     for(int i = 1; i <= 5; i++){
        getline(cin, s);
        if(i != 3 ) Map[i][s].insert(id);
        else {
          stringstream xx(s);
          while(xx >> s) Map[i][s].insert(id);
        }
     }
  }

  cin >> M;
  while(M--){
     int a;
     scanf("%d: ", &a);
     getline(cin, s);
     cout<<a<<": "<<s<<endl;
     set<int> &temp =  Map[a][s] ;
     if(temp.empty()) cout<<"Not Found\n";
     else for(auto i : temp)  printf("%07d\n",i);
  }
  return 0;
}

 

 

 

------------------------------------------------------------------------------------------------------------------------------------

1023 Have Fun with Numbers (20)(20 分)

Notice that the number 123456789 is a 9-digit number consisting exactly the numbers from 1 to 9, with no duplication. Double it we will obtain 246913578, which happens to be another 9-digit number consisting exactly the numbers from 1 to 9, only in a different permutation. Check to see the result if we double it again!

Now you are suppose to check if there are more numbers with this property. That is, double a given number with k digits, you are to tell if the resulting number consists of only a permutation of the digits in the original number.

Input Specification:

Each input file contains one test case. Each case contains one positive integer with no more than 20 digits.

Output Specification:

For each test case, first print in a line "Yes" if doubling the input number gives a number that consists of only a permutation of the digits in the original number, or "No" if not. Then in the next line, print the doubled number.

Sample Input:

1234567899

Sample Output:

Yes
2469135798

 

 

#include<bits/stdc++.h>
using namespace std;

int main(){
   string s, sum, sum0;
   cin >> s;
   reverse(s.begin(), s.end() );
   int len = s.length(), c = 0;
   for(int i = 0; i < len; i++){
      int t = (s[i]-'0')*2 + c;
      sum += (t%10 + '0');
      c = t / 10;
   }
   if(c) sum += '1';
   reverse(sum.begin(), sum.end() );
   sum0 = sum;
   sort(s.begin(), s.end());
   sort(sum.begin(), sum.end());
   if(s == sum) cout<<"Yes\n";
   else cout<<"No\n";
   cout<<sum0<<endl;
   return 0;  
} 

 

 

 

 

--------------------------------------------------------------------------------------------------------------------------------------------------------------

1024 Palindromic Number (25)(25 分)

A number that will be the same when it is written forwards or backwards is known as a Palindromic Number. For example, 1234321 is a palindromic number. All single digit numbers are palindromic numbers.

Non-palindromic numbers can be paired with palindromic ones via a series of operations. First, the non-palindromic number is reversed and the result is added to the original number. If the result is not a palindromic number, this is repeated until it gives a palindromic number. For example, if we start from 67, we can obtain a palindromic number in 2 steps: 67 + 76 = 143, and 143 + 341 = 484.

Given any positive integer N, you are supposed to find its paired palindromic number and the number of steps taken to find it.

Input Specification:

Each input file contains one test case. Each case consists of two positive numbers N and K, where N (<= 10^10^) is the initial numer and K (<= 100) is the maximum number of steps. The numbers are separated by a space.

Output Specification:

For each test case, output two numbers, one in each line. The first number is the paired palindromic number of N, and the second number is the number of steps taken to find the palindromic number. If the palindromic number is not found after K steps, just output the number obtained at the Kth step and K instead.

Sample Input 1:

67 3

Sample Output 1:

484
2

Sample Input 2:

69 3

Sample Output 2:

1353
3

 

 

#include<bits/stdc++.h>
using namespace std;

string Getsum(string s){
   string sum, s0 = s;
   int c = 0, len = s.length();
   reverse(s.begin(), s.end() );
   for(int i = 0; i < len; i++){
      int t = (s[i] + s0[i] - 2 *'0' + c);
      sum += (t%10 + '0');
      c = t / 10;
   }
   if(c) sum += '1';
   reverse(sum.begin(), sum.end() );
   return sum;
}

bool ispalindeomic(string s){
   string s0 = s;
   reverse(s0.begin(), s0.end());
   if(s0 == s) return true;
   else return false;
}

int main(){
   string s;
   int N, T = 0;
   cin >> s >> N;
   if(ispalindeomic(s) ){
      cout<<s<<"\n0\n";
      return 0;
   }
   while(N--){
      T++;
      if( ispalindeomic( s = Getsum(s)  ) ) break;
   }
   cout<<s<<endl<<T<<endl;
   return 0;
}

 

 

 

 

--------------------------------------------------------------------------------------------------------------------------------------------------------------------

1025 PAT Ranking (25)(25 分)

Programming Ability Test (PAT) is organized by the College of Computer Science and Technology of Zhejiang University. Each test is supposed to run simultaneously in several places, and the ranklists will be merged immediately after the test. Now it is your job to write a program to correctly merge all the ranklists and generate the final rank.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive number N (<=100), the number of test locations. Then N ranklists follow, each starts with a line containing a positive integer K (<=300), the number of testees, and then K lines containing the registration number (a 13-digit number) and the total score of each testee. All the numbers in a line are separated by a space.

Output Specification:

For each test case, first print in one line the total number of testees. Then print the final ranklist in the following format:

registration_number final_rank location_number local_rank

The locations are numbered from 1 to N. The output must be sorted in nondecreasing order of the final ranks. The testees with the same score must have the same rank, and the output must be sorted in nondecreasing order of their registration numbers.

Sample Input:

2
5
1234567890001 95
1234567890005 100
1234567890003 95
1234567890002 77
1234567890004 85
4
1234567890013 65
1234567890011 25
1234567890014 100
1234567890012 85

Sample Output:

9
1234567890005 1 1 1
1234567890014 1 2 1
1234567890001 3 1 2
1234567890003 3 1 2
1234567890004 5 1 4
1234567890012 5 2 2
1234567890002 7 1 5
1234567890013 8 2 3
1234567890011 9 2 4

 

 

#include<bits/stdc++.h>
using namespace std;

const int maxn = 105*305;
int N, K, i = 0, start;
struct node{
   char id[20];
   int  point, final_rank, location_number, local_rank;
   bool operator < (const node &rhs ) const {
     return (point == rhs.point)? (strcmp(id, rhs.id) < 0) : (point > rhs.point);
   }
}stu[maxn];

int main(){
   cin >> N;
   for(int t = 1; t <= N; t++){
      cin >> K;
      start = i;
      while(K--){
         scanf("%s%d",stu[i].id, &stu[i].point);
         stu[i++].location_number = t;
      }
      sort(stu+start, stu+i);
      stu[start].local_rank = 1;
      for(int j = start+1, k = 2; j < i; j++, k++){
         if(stu[j].point == stu[j-1].point) stu[j].local_rank = stu[j-1].local_rank;
         else stu[j].local_rank = k;
      }
   }
   sort(stu, stu+i);
   stu[0].final_rank = 1;
   for(int j = 1; j < i; j++){
       if(stu[j].point == stu[j-1].point) stu[j].final_rank = stu[j-1].final_rank;
       else stu[j].final_rank = j+1;
   }
   cout<<i<<endl;
   for(int j = 0; j < i; j++)
      printf("%s %d %d %d\n",stu[j].id, stu[j].final_rank, stu[j].location_number, stu[j].local_rank);
   return 0;
}

 

 

 

------------------------------------------------------------------------------------------------------------------------------------------------------

1026 Table Tennis (30)(30 分)

A table tennis club has N tables available to the public. The tables are numbered from 1 to N. For any pair of players, if there are some tables open when they arrive, they will be assigned to the available table with the smallest number. If all the tables are occupied, they will have to wait in a queue. It is assumed that every pair of players can play for at most 2 hours.

Your job is to count for everyone in queue their waiting time, and for each table the number of players it has served for the day.

One thing that makes this procedure a bit complicated is that the club reserves some tables for their VIP members. When a VIP table is open, the first VIP pair in the queue will have the priviledge to take it. However, if there is no VIP in the queue, the next pair of players can take it. On the other hand, if when it is the turn of a VIP pair, yet no VIP table is available, they can be assigned as any ordinary players.

Input Specification:

Each input file contains one test case. For each case, the first line contains an integer N (<=10000) - the total number of pairs of players. Then N lines follow, each contains 2 times and a VIP tag: HH:MM:SS - the arriving time, P - the playing time in minutes of a pair of players, and tag - which is 1 if they hold a VIP card, or 0 if not. It is guaranteed that the arriving time is between 08:00:00 and 21:00:00 while the club is open. It is assumed that no two customers arrives at the same time. Following the players' info, there are 2 positive integers: K (<=100) - the number of tables, and M (< K) - the number of VIP tables. The last line contains M table numbers.

Output Specification:

For each test case, first print the arriving time, serving time and the waiting time for each pair of players in the format shown by the sample. Then print in a line the number of players served by each table. Notice that the output must be listed in chronological order of the serving time. The waiting time must be rounded up to an integer minute(s). If one cannot get a table before the closing time, their information must NOT be printed.

Sample Input:

9
20:52:00 10 0
08:00:00 20 0
08:02:00 30 0
20:51:00 10 0
08:10:00 5 0
08:12:00 10 1
20:50:00 10 0
08:01:30 15 1
20:53:00 10 1
3 1
2

Sample Output:

08:00:00 08:00:00 0
08:01:30 08:01:30 0
08:02:00 08:02:00 0
08:12:00 08:16:30 5
08:10:00 08:20:00 10
20:50:00 20:50:00 0
20:51:00 20:51:00 0
20:52:00 20:52:00 0
3 3 2

 

 

 

 

-------------------------------------------------------------------------------------------------------------------------------------------------------

1027 Colors in Mars (20)(20 分)

People in Mars represent the colors in their computers in a similar way as the Earth people. That is, a color is represented by a 6-digit number, where the first 2 digits are for Red, the middle 2 digits for Green, and the last 2 digits for Blue. The only difference is that they use radix 13 (0-9 and A-C) instead of 16. Now given a color in three decimal numbers (each between 0 and 168), you are supposed to output their Mars RGB values.

Input

Each input file contains one test case which occupies a line containing the three decimal color values.

Output

For each test case you should output the Mars RGB value in the following format: first output "#", then followed by a 6-digit number where all the English characters must be upper-cased. If a single color is only 1-digit long, you must print a "0" to the left.

Sample Input

15 43 71

Sample Output

#123456

 

#include<bits/stdc++.h>
using namespace std;

void MarColor(int n){
   if(n < 10) cout<<n;
   else cout << char(n-10+'A');
   return;
}

int main(){
   int T = 3, n;
   cout << '#';
   while(T--){
      cin >> n;
      MarColor( n/13 );
      MarColor( n%13 );
   }
   return 0;
}

 

 

 

-----------------------------------------------------------------------------------------------------------------------------------------------------------

1028 List Sorting (25)(25 分)

Excel can sort records according to any column. Now you are supposed to imitate this function.

Input

Each input file contains one test case. For each case, the first line contains two integers N (<=100000) and C, where N is the number of records and C is the column that you are supposed to sort the records with. Then N lines follow, each contains a record of a student. A student's record consists of his or her distinct ID (a 6-digit number), name (a string with no more than 8 characters without space), and grade (an integer between 0 and 100, inclusive).

Output

For each test case, output the sorting result in N lines. That is, if C = 1 then the records must be sorted in increasing order according to ID's; if C = 2 then the records must be sorted in non-decreasing order according to names; and if C = 3 then the records must be sorted in non-decreasing order according to grades. If there are several students who have the same name or grade, they must be sorted according to their ID's in increasing order.

Sample Input 1

3 1
000007 James 85
000010 Amy 90
000001 Zoe 60

Sample Output 1

000001 Zoe 60
000007 James 85
000010 Amy 90

Sample Input 2

4 2
000007 James 85
000010 Amy 90
000001 Zoe 60
000002 James 98

Sample Output 2

000010 Amy 90
000002 James 98
000007 James 85
000001 Zoe 60

Sample Input 3

4 3
000007 James 85
000010 Amy 90
000001 Zoe 60
000002 James 90

Sample Output 3

000001 Zoe 60
000007 James 85
000002 James 90
000010 Amy 90

 

#include<bits/stdc++.h>
using namespace std;

const int maxn = 100000+5;
int N, C;
struct node{
   int id, point;
   char name[10];
   bool operator < (const node &rhs) const{
      if(C == 1) return id < rhs.id;
      else if(C == 2) return (strcmp(name, rhs.name) == 0 )? (id < rhs.id): (strcmp(name, rhs.name) < 0);
      else return (point == rhs.point)? (id < rhs.id): (point < rhs.point);
   }
}stu[maxn];

int main(){
   cin >> N >> C;
   for(int i = 0; i < N; i++) scanf("%d%s%d",&stu[i].id, stu[i].name, &stu[i].point);
   sort(stu, stu+N);
   for(int i = 0; i < N; i++) printf("%06d %s %d\n",stu[i].id, stu[i].name, stu[i].point);
   return 0;
}

 

 

 

 

----------------------------------------------------------------------------------------------------------------------------------------------------------

1029 Median(25 分)

Given an increasing sequence S of N integers, the median is the number at the middle position. For example, the median of S1 = { 11, 12, 13, 14 } is 12, and the median of S2 = { 9, 10, 15, 16, 17 } is 15. The median of two sequences is defined to be the median of the nondecreasing sequence which contains all the elements of both sequences. For example, the median of S1 and S2 is 13.

Given two increasing sequences of integers, you are asked to find their median.

Input Specification:

Each input file contains one test case. Each case occupies 2 lines, each gives the information of a sequence. For each sequence, the first positive integer N (≤2×10​5​​) is the size of that sequence. Then N integers follow, separated by a space. It is guaranteed that all the integers are in the range of long int.

Output Specification:

For each test case you should output the median of the two given sequences in a line.

Sample Input:

4 11 12 13 14
5 9 10 15 16 17

Sample Output:

13

 

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2e5+10;

int k[MAXN];

int main(){
    int n, m, t, cnt = 0;
    cin >> n;
    for (int i = 1; i <= n; i++)  scanf("%d", &k[i]);
    k[n + 1] = 0x7fffffff;
    cin >> m;
    int mid = (n+m+1) / 2, i = 1;
    bool ok = false;
    while( m-- ) {
        scanf("%d", &t);
        while ( k[i] < t) {
            if (++cnt == mid) { cout << k[i]; ok = true; break; }
            i++;
        }
        if (++cnt == mid) { cout << t; ok = true; break; }
    }
    while (!ok && i <= n) {
        if (++cnt == mid) { cout << k[i]; break; }
        i++;
    }
    

 

 

 

 

 

 

----------------------------------------------------------------------------------------------------------------------------------------------------------

1030 Travel Plan (30)(30 分)

A traveler's map gives the distances between cities along the highways, together with the cost of each highway. Now you are supposed to write a program to help a traveler to decide the shortest path between his/her starting city and the destination. If such a shortest path is not unique, you are supposed to output the one with the minimum cost, which is guaranteed to be unique.

Input Specification:

Each input file contains one test case. Each case starts with a line containing 4 positive integers N, M, S, and D, where N (<=500) is the number of cities (and hence the cities are numbered from 0 to N-1); M is the number of highways; S and D are the starting and the destination cities, respectively. Then M lines follow, each provides the information of a highway, in the format:

City1 City2 Distance Cost

where the numbers are all integers no more than 500, and are separated by a space.

Output Specification:

For each test case, print in one line the cities along the shortest path from the starting point to the destination, followed by the total distance and the total cost of the path. The numbers must be separated by a space and there must be no extra space at the end of output.

Sample Input

4 5 0 3
0 1 1 20
1 3 2 30
0 3 4 10
0 2 2 20
2 3 1 20

Sample Output

0 2 3 3 
#include<bits/stdc++.h>
using namespace std;

const int maxn = 500+5, inf = 9999999;
int N, M, S, D;
int d[maxn][maxn], w[maxn][maxn];
int dis[maxn], cost[maxn], v[maxn], fa[maxn];

int main(){
   cin >> N >> M >> S >> D;
   while( M-- ){
      int City1, City2, Distance, Cost;
      scanf("%d%d%d%d",&City1, &City2, &Distance, &Cost);
      d[City1][City2] = d[City2][City1] = Distance;
      w[City1][City2] = w[City2][City1] = Cost;
   }
   for(int i = 0; i < N; i++) dis[i] = (i == S ? 0 : inf);
   for(int i = 0; i < N; i++){
      int x = -1, m = inf;
      for(int y = 0; y < N ; y++) if(!v[y] && dis[y] < m) m = dis[x = y];
      if(x == -1) break;
      v[x] = 1;
      for(int y = 0; y < N; y++) if(!v[y] && d[x][y]){
        if( dis[y] > dis[x] + d[x][y] || ( dis[y] == dis[x] + d[x][y]  && cost[y] > cost[x] + w[x][y]) ){
            dis[y] = dis[x] + d[x][y];
            cost[y] = cost[x] + w[x][y];
            fa[y] = x;
         }
      }
   }
   vector< int > temp;
   for(int i = D;; i = fa[i]){
      temp.push_back(i);
      if(i == S) break;
   }
   for(int i = temp.size()-1; i >= 0; i--) cout << temp[i] << " " ;
   cout << dis[D] << " " << cost[D] << endl;
   return 0;
}

 

 

 

 

 

 

--------------------------------------------------------------------------------------------------------------------------------------------------------------

1031 Hello World for U (20)(20 分)

Given any string of N (>=5) characters, you are asked to form the characters into the shape of U. For example, "helloworld" can be printed as:

h  d
e  l
l  r
lowo

That is, the characters must be printed in the original order, starting top-down from the left vertical line with n~1~ characters, then left to right along the bottom line with n~2~ characters, and finally bottom-up along the vertical line with n~3~ characters. And more, we would like U to be as squared as possible -- that is, it must be satisfied that n~1~ = n~3~ = max { k| k <= n~2~ for all 3 <= n~2~ <= N } with n~1~

  • n~2~ + n~3~ - 2 = N.

Input Specification:

Each input file contains one test case. Each case contains one string with no less than 5 and no more than 80 characters in a line. The string contains no white space.

Output Specification:

For each test case, print the input string in the shape of U as specified in the description.

Sample Input:

helloworld!

Sample Output:

h   !
e   d
l   l
lowor

 

 

#include<bits/stdc++.h>
using namespace std;

int main(){
   string s;
   cin >> s;
   int len = s.length(), k = (len+2)/3-1, n = len-2*k-2; 
   for(int i = 0; i < k; i++){
      cout << s[i];
      for(int j = 1; j <= n; j++) cout <<" ";
      cout << s[len-1-i]<<endl;
   }
   for(int i = k; i <= len-1-k; i++) cout << s[i];
   return 0;
}

 

 

 

 

-------------------------------------------------------------------------------------------------------------------------------------

1032 Sharing (25)(25 分)

To store English words, one method is to use linked lists and store a word letter by letter. To save some space, we may let the words share the same sublist if they share the same suffix. For example, "loading" and "being" are stored as showed in Figure 1.

\ Figure 1

You are supposed to find the starting position of the common suffix (e.g. the position of "i" in Figure 1).

Input Specification:

Each input file contains one test case. For each case, the first line contains two addresses of nodes and a positive N (<= 10^5^), where the two addresses are the addresses of the first nodes of the two words, and N is the total number of nodes. The address of a node is a 5-digit positive integer, and NULL is represented by -1.

Then N lines follow, each describes a node in the format:

Address Data Next

where Address is the position of the node, Data is the letter contained by this node which is an English letter chosen from {a-z, A-Z}, and Next is the position of the next node.

Output Specification:

For each case, simply output the 5-digit starting position of the common suffix. If the two words have no common suffix, output "-1" instead.

Sample Input 1:

11111 22222 9
67890 i 00002
00010 a 12345
00003 g -1
12345 D 67890
00002 n 00003
22222 B 23456
11111 L 00001
23456 e 67890
00001 o 00010

Sample Output 1:

67890

Sample Input 2:

00001 00002 4
00001 a 10001
10001 s -1
00002 a 10002
10002 t -1

Sample Output 2:

-1

 

 

#include <bits/stdc++.h>
using namespace std;

const int maxn = 100000;
int Next[maxn];

int main(){
   int p, q, n, a, b;
   char c;
   cin >> p >>q >> n;
   while(n--){
      scanf("%d %c %d",&a, &c, &b);
      Next[a] = b;
   }
   unordered_set< int >Set;
   while(p != -1){
     Set.insert(p);
     p = Next[p];
   }
   while(q != -1){
     if( Set.count(q) ) break;
     q = Next[q];
   }
   if(q == -1) cout<<-1<<endl;
   else printf("%05d",q);
   return 0;
}

 

 

 

 

-------------------------------------------------------------------------------------------------------------------------------------------------------------------

1033 To Fill or Not to Fill (25)(25 分)

With highways available, driving a car from Hangzhou to any other city is easy. But since the tank capacity of a car is limited, we have to find gas stations on the way from time to time. Different gas station may give different price. You are asked to carefully design the cheapest route to go.

Input Specification:

Each input file contains one test case. For each case, the first line contains 4 positive numbers: C~max~ (<= 100), the maximum capacity of the tank; D (<=30000), the distance between Hangzhou and the destination city; D~avg~ (<=20), the average distance per unit gas that the car can run; and N (<= 500), the total number of gas stations. Then N lines follow, each contains a pair of non-negative numbers: P~i~, the unit gas price, and D~i~ (<=D), the distance between this station and Hangzhou, for i=1,...N. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the cheapest price in a line, accurate up to 2 decimal places. It is assumed that the tank is empty at the beginning. If it is impossible to reach the destination, print "The maximum travel distance = X" where X is the maximum possible distance the car can run, accurate up to 2 decimal places.

Sample Input 1:

50 1300 12 8
6.00 1250
7.00 600
7.00 150
7.10 0
7.20 200
7.50 400
7.30 1000
6.85 300

Sample Output 1:

749.17

Sample Input 2:

50 1300 12 2
7.10 0
7.00 600

Sample Output 2:

The maximum travel distance = 1200.00

 

 

#include <bits/stdc++.h>
using namespace std;

int C, D, P, N;
vector< pair<int, double> >v;

void init(){
   cin >> C >> D >> P >> N;
   v.push_back( make_pair(D,0.0) );
   for(int i = 0; i < N; i++){
      double p;  int dist;
      scanf("%lf%d", &p, &dist);
      v.push_back( make_pair(dist,p) );
   }
   sort(v.begin(), v.end());
}

void simulation(){
   int p = 0, i = 0;
   double left = 0.0, sum = 0.0, farest;
   while(p != D){
       farest = p + C*P;
       int j = i+1, cnt = 0;
       while(v[j].first <= farest){
           cnt++;
           if(v[j].second <= v[i].second) break;
           j++;
       }
       if( !cnt ) { printf("The maximum travel distance = %.2f\n", farest); return;}
       else if( v[j].first > farest ){
          sum += (C-left)*v[i].second;
          left = C - ( v[ j = i+1 ].first - v[i].first )*1.0/P;
       }
       else {
          double need = (v[j].first - v[i].first)*1.0/P;
          if(need > left){
             sum += (need-left)*v[i].second;
             left = 0;
          }
          else left = left - need;
       }
       p = v[ i = j].first;
   }
   printf("%.2f\n", sum);
}

int main(){
   init();
   simulation();
   return 0;
}

 

 

 

 

 

 

--------------------------------------------------------------------------------------------------------------------------------------------------------------------

1034 Head of a Gang (30)(30 分)

One way that the police finds the head of a gang is to check people's phone calls. If there is a phone call between A and B, we say that A and B is related. The weight of a relation is defined to be the total time length of all the phone calls made between the two persons. A "Gang" is a cluster of more than 2 persons who are related to each other with total relation weight being greater than a given threshold K. In each gang, the one with maximum total weight is the head. Now given a list of phone calls, you are supposed to find the gangs and the heads.

Input Specification:

Each input file contains one test case. For each case, the first line contains two positive numbers N and K (both less than or equal to 1000), the number of phone calls and the weight threshold, respectively. Then N lines follow, each in the following format:

Name1 Name2 Time

where Name1 and Name2 are the names of people at the two ends of the call, and Time is the length of the call. A name is a string of three capital letters chosen from A-Z. A time length is a positive integer which is no more than 1000 minutes.

Output Specification:

For each test case, first print in a line the total number of gangs. Then for each gang, print in a line the name of the head and the total number of the members. It is guaranteed that the head is unique for each gang. The output must be sorted according to the alphabetical order of the names of the heads.

Sample Input 1:

8 59
AAA BBB 10
BBB AAA 20
AAA CCC 40
DDD EEE 5
EEE DDD 70
FFF GGG 30
GGG HHH 20
HHH FFF 10

Sample Output 1:

2
AAA 3
GGG 3

Sample Input 2:

8 70
AAA BBB 10
BBB AAA 20
AAA CCC 40
DDD EEE 5
EEE DDD 70
FFF GGG 30
GGG HHH 20
HHH FFF 10

Sample Output 2:

0
#include<bits/stdc++.h>
using namespace std;

const int MAXN = 2e3+10;
int N, K, n = 0, t;
char name1[4], name2[4];
int fa[MAXN], Time[MAXN];
map<int, int> IDCache;
map<int, int> NameCache;

int find( int x ){
	return x == fa[x] ? x : ( fa[x] = find ( fa[x] ) );
}

int getid( char *a ){
   int k = (a[0]-'A')*26*26 + (a[1]-'A')*26 + a[2]-'A';
   if( IDCache.find(k) == IDCache.end() ){
   	  IDCache[k] = n;
   	  NameCache[n++] = k;
   }
   return IDCache[k];
}

void Union(int x, int y, int t){
	Time[x] += t;    Time[y] += t;
	fa[ find(x) ] = find(y);
}

struct node{
	int Sum, Name, p, MAX;
	bool operator < (const node &rhs) const{
	   return Name < rhs.Name;
	}
};

vector< node > Ans;

void print(){
   sort(Ans.begin(), Ans.end());
   cout << Ans.size() << endl;
   for(int i = 0; i < Ans.size(); i++){
      int name = Ans[i].Name;
   	  printf("%c%c%c %d\n", name/26/26+'A', (name/26)%26+'A', name%26+'A', Ans[i].p );
   }
}

int main(){
   for(int i = 0; i < MAXN; i++) fa[i] = i;
   cin >> N >> K;
   while( N-- ){
      scanf("%s%s%d", name1, name2, &t);
   	  Union( getid( name1 ), getid( name2 ), t );
   }
   map< int, node > Mymap;	
   for(int y = 0; y < n; y++){
   	  int x = find(y);
	    Mymap[x].Sum += Time[y];
	    Mymap[x].p++;
	    if( Mymap[x].MAX < Time[y] ){
	        Mymap[x].Name = NameCache[y];
	        Mymap[x].MAX = Time[y];
	    }
   }
   
   for(map<int, node > :: iterator it = Mymap.begin(); it != Mymap.end(); it++)
      if( it->second.Sum > 2*K && it->second.p > 2)
   	     Ans.push_back( it->second );
   print();
   return 0;
} 

 

 

 

-------------------------------------------------------------------------------------------------------------------------------------------------------------

1035 Password (20)(20 分)

To prepare for PAT, the judge sometimes has to generate random passwords for the users. The problem is that there are always some confusing passwords since it is hard to distinguish 1 (one) from l (L in lowercase), or 0 (zero) from O (o in uppercase). One solution is to replace 1 (one) by @, 0 (zero) by %, l by L, and O by o. Now it is your job to write a program to check the accounts generated by the judge, and to help the juge modify the confusing passwords.

Input Specification:

Each input file contains one test case. Each case contains a positive integer N (<= 1000), followed by N lines of accounts. Each account consists of a user name and a password, both are strings of no more than 10 characters with no space.

Output Specification:

For each test case, first print the number M of accounts that have been modified, then print in the following M lines the modified accounts info, that is, the user names and the corresponding modified passwords. The accounts must be printed in the same order as they are read in. If no account is modified, print in one line "There are N accounts and no account is modified" where N is the total number of accounts. However, if N is one, you must print "There is 1 account and no account is modified" instead.

Sample Input 1:

3
Team000002 Rlsp0dfa
Team000003 perfectpwd
Team000001 R1spOdfa

Sample Output 1:

2
Team000002 RLsp%dfa
Team000001 R@spodfa

Sample Input 2:

1
team110 abcdefg332

Sample Output 2:

There is 1 account and no account is modified

Sample Input 3:

2
team110 abcdefg222
team220 abcdefg333

Sample Output 3:

There are 2 accounts and no account is modified

 

 

#include<bits/stdc++.h>
using namespace std;

int main(){
   int N;
   string name, password;
   vector< string >v;
   cin >> N;
   for(int k = 0; k < N; k++){
      cin >> name >> password;
      bool ok = true;
      for(int i = 0; i < password.length(); i++){
         if(password[i] == '1')  { password[i] = '@'; ok = false;}
         else if(password[i] == '0') { password[i] = '%'; ok = false; }
         else if(password[i] == 'O') { password[i] = 'o'; ok = false; }
         else if(password[i] == 'l') { password[i] = 'L'; ok = false; }
      }
      if(!ok) { v.push_back(name); v.push_back(password); }
   }
   if( v.empty() ) printf("There %s %d account%sand no account is modified", (N == 1)?"is": "are", N, (N == 1)?" ": "s " );
   else {
      cout << v.size()/2 <<endl;
      for(int i = 0; i < (int)v.size(); i += 2)
         cout << v[i] << " " << v[i+1] << endl;
   }
   return 0;
}

 

 

 

 

 

 

------------------------------------------------------------------------------------------------------------------------------------------------------------------------

1036 Boys vs Girls (25)(25 分)

This time you are asked to tell the difference between the lowest grade of all the male students and the highest grade of all the female students.

Input Specification:

Each input file contains one test case. Each case contains a positive integer N, followed by N lines of student information. Each line contains a student's name, gender, ID and grade, separated by a space, where name and ID are strings of no more than 10 characters with no space, gender is either F (female) or M (male), and grade is an integer between 0 and 100. It is guaranteed that all the grades are distinct.

Output Specification:

For each test case, output in 3 lines. The first line gives the name and ID of the female student with the highest grade, and the second line gives that of the male student with the lowest grade. The third line gives the difference grade~F~-grade~M~. If one such kind of student is missing, output "Absent" in the corresponding line, and output "NA" in the third line instead.

Sample Input 1:

3
Joe M Math990112 89
Mike M CS991301 100
Mary F EE990830 95

Sample Output 1:

Mary EE990830
Joe Math990112
6

Sample Input 2:

1
Jean M AA980920 60

Sample Output 2:

Absent
Jean AA980920
NA

 

 

#include<bits/stdc++.h>
using namespace std;

const int inf = 999999;

string female_id, male_id, female_name, male_name;
int female_point = -inf, male_point = inf;

int main(){
   int N, point;
   char c;
   string name, id;

   cin >> N;
   while( N-- ){
      cin >> name >> c >> id >> point;
      if( c == 'M' && point < male_point) { male_id = id; male_name = name; male_point = point; }
      else if( c == 'F' && point > female_point) { female_id = id; female_name = name; female_point = point; }
   }
   bool ok = true;
   if(female_point == -inf) { cout << "Absent\n"; ok = false; }
   else cout << female_name << " " << female_id <<endl;
   if(male_point == inf) { cout << "Absent\n";  ok = false; }
   else  cout << male_name << " " << male_id <<endl;

   if(ok) cout << female_point - male_point << endl;
   else cout<<"NA\n";
   return 0;
}

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------------------------------------

1037 Magic Coupon (25)(25 分)

The magic shop in Mars is offering some magic coupons. Each coupon has an integer N printed on it, meaning that when you use this coupon with a product, you may get N times the value of that product back! What is more, the shop also offers some bonus product for free. However, if you apply a coupon with a positive N to this bonus product, you will have to pay the shop N times the value of the bonus product... but hey, magically, they have some coupons with negative N's!

For example, given a set of coupons {1 2 4 -1}, and a set of product values {7 6 -2 -3} (in Mars dollars M\$) where a negative value corresponds to a bonus product. You can apply coupon 3 (with N being 4) to product 1 (with value M\$7) to get M\$28 back; coupon 2 to product 2 to get M\$12 back; and coupon 4 to product 4 to get M\$3 back. On the other hand, if you apply coupon 3 to product 4, you will have to pay M\$12 to the shop.

Each coupon and each product may be selected at most once. Your task is to get as much money back as possible.

Input Specification:

Each input file contains one test case. For each case, the first line contains the number of coupons NC, followed by a line with NC coupon integers. Then the next line contains the number of products NP, followed by a line with NP product values. Here 1<= NC, NP <= 10^5^, and it is guaranteed that all the numbers will not exceed 2^30^.

Output Specification:

For each test case, simply print in a line the maximum amount of money you can get back.

Sample Input:

4
1 2 4 -1
4
7 6 -2 -3

Sample Output:

43

 

#include<bits/stdc++.h>
using namespace std;

int N, sum = 0, a;
vector< int > v[2];

int main(){
  for(int i = 0; i < 2; i++){
     cin >> N;
     while(N--){
       scanf("%d", &a);
       v[i].push_back(a);
     }
     sort(v[i].begin(), v[i].end());
  }
  int p = v[0].size(), q = v[1].size();
  for(int i = 0; i < p && i < q; i++){
     if(v[0][i] < 0 && v[1][i] < 0) sum += v[0][i]*v[1][i];
     else break;
  }
  for(int i = p-1, j = q-1; i >= 0 && j >= 0; i--, j--){
     if(v[0][i] > 0 && v[1][j] > 0) sum += v[0][i]*v[1][j];
     else break;
  }
  cout << sum << endl;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------------------------------------------------

1038 Recover the Smallest Number (30)(30 分)

Given a collection of number segments, you are supposed to recover the smallest number from them. For example, given {32, 321, 3214, 0229, 87}, we can recover many numbers such like 32-321-3214-0229-87 or 0229-32-87-321-3214 with respect to different orders of combinations of these segments, and the smallest number is 0229-321-3214-32-87.

Input Specification:

Each input file contains one test case. Each case gives a positive integer N (<=10000) followed by N number segments. Each segment contains a non-negative integer of no more than 8 digits. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the smallest number in one line. Do not output leading zeros.

Sample Input:

5 32 321 3214 0229 87

Sample Output:

22932132143287

 

#include<bits/stdc++.h>
using namespace std;

int N;
string s;
vector< string > v;
bool cmp (string a, string b){
  return a + b < b +a;
}

int main(){
   cin >> N;
   v.resize(N);
   for(int i = 0; i < N; i++)  cin >> v[i];
   sort(v.begin(), v.end(), cmp);
   string sum;
   for(auto i : v) sum += i;
   int len = sum.length(), start = 0;
   for(; start < len; start++)
      if(sum[start] != '0') break;
   if( start == len ) cout << "0\n";
   else for(int i = start; i < len; i++)
     cout<< sum[i];
   return 0;
}

 

 

 

 

 

 

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

1039 Course List for Student (25)(25 分)

Zhejiang University has 40000 students and provides 2500 courses. Now given the student name lists of all the courses, you are supposed to output the registered course list for each student who comes for a query.

Input Specification:

Each input file contains one test case. For each case, the first line contains 2 positive integers: N (<=40000), the number of students who look for their course lists, and K (<=2500), the total number of courses. Then the student name lists are given for the courses (numbered from 1 to K) in the following format: for each course i, first the course index i and the number of registered students N~i~ (<= 200) are given in a line. Then in the next line, N~i~ student names are given. A student name consists of 3 capital English letters plus a one-digit number. Finally the last line contains the N names of students who come for a query. All the names and numbers in a line are separated by a space.

Output Specification:

For each test case, print your results in N lines. Each line corresponds to one student, in the following format: first print the student's name, then the total number of registered courses of that student, and finally the indices of the courses in increasing order. The query results must be printed in the same order as input. All the data in a line must be separated by a space, with no extra space at the end of the line.

Sample Input:

11 5
4 7
BOB5 DON2 FRA8 JAY9 KAT3 LOR6 ZOE1
1 4
ANN0 BOB5 JAY9 LOR6
2 7
ANN0 BOB5 FRA8 JAY9 JOE4 KAT3 LOR6
3 1
BOB5
5 9
AMY7 ANN0 BOB5 DON2 FRA8 JAY9 KAT3 LOR6 ZOE1
ZOE1 ANN0 BOB5 JOE4 JAY9 FRA8 DON2 AMY7 KAT3 LOR6 NON9

Sample Output:

 

#include<bits/stdc++.h>
using namespace std;

const int maxn = 26 * 26 * 26 * 10 + 10;
int N, K, C, M;
char name[maxn];
map< int, set<int> > Map;

int getid(char* name){
   return (name[0] - 'A')*26*26*10 + (name[1] - 'A')*26*10 + (name[2] - 'A')*10 + (name[3] - '0');
}

vector<int> v[maxn];

int main() {
    cin >> N >> K;
    while( K-- ){
       cin >> C >> M;
       while( M-- ){
          scanf("%s", name);
          v[ getid(name) ].push_back( C );
       }
   }
    while( scanf("%s", name) != EOF){
      int id = getid(name);
      printf("%s %d", name, v[id].size());
      sort(v[id].begin(), v[id].end());
      for(auto i : v[id]) printf(" %d", i);
      putchar('\n');
   }
   return 0;
}

 

 

 

 

 

 

 

-----------------------------------------------------------------------------------------------------------------------------------------------------------

1040 Longest Symmetric String (25)(25 分)

Given a string, you are supposed to output the length of the longest symmetric sub-string. For example, given "Is PAT&TAP symmetric?", the longest symmetric sub-string is "s PAT&TAP s", hence you must output 11.

Input Specification:

Each input file contains one test case which gives a non-empty string of length no more than 1000.

Output Specification:

For each test case, simply print the maximum length in a line.

Sample Input:

Is PAT&TAP symmetric?

Sample Output:

11
#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1e3+10;
int dp[MAXN][MAXN], Maxlength = 1;

int main(){
   string s;
   getline(cin, s);
   int n = s.length();
   for(int i = 0; i < n; i++){
   	  dp[i][i] = 1;
	    if(i && s[i-1] == s[i] ) dp[i-1][i] = Maxlength = 2;
   }
   for(int k = 3; k <= n; k++)
   	  for(int j = 0; j+k-1 < n; j++)
   	  	 if( s[j+k-1] == s[j] && dp[j+1][j+k-2] == k-2 ) dp[j][j+k-1] = Maxlength = k;
   cout << Maxlength << endl;
   return 0;
}

 

 

 

 

 

 

-----------------------------------------------------------------------------------------------------------------------------------------------------------

1041 Be Unique (20)(20 分)

Being unique is so important to people on Mars that even their lottery is designed in a unique way. The rule of winning is simple: one bets on a number chosen from [1, 10^4^]. The first one who bets on a unique number wins. For example, if there are 7 people betting on 5 31 5 88 67 88 17, then the second one who bets on 31 wins.

Input Specification:

Each input file contains one test case. Each case contains a line which begins with a positive integer N (<=10^5^) and then followed by N bets. The numbers are separated by a space.

Output Specification:

For each test case, print the winning number in a line. If there is no winner, print "None" instead.

Sample Input 1:

7 5 31 5 88 67 88 17

Sample Output 1:

31

Sample Input 2:

5 888 666 666 888 888

Sample Output 2:

None

 

 

 

#include<bits/stdc++.h>
using namespace std;

const int maxn = 1e5+10;
int a[maxn], b[maxn];

int main(){
   int n, x;
   cin >> n;
   for(int i = 0; i < n; i++){
      scanf("%d", &x);
      a[ b[i] = x ]++;
   }
   for(int i = 0;i < n; i++){
      if(a[ b[i] ] == 1){
         cout << b[i] << endl;
         return 0;
      }
   }
   cout << "None" << endl;
   return 0;
}

 

 

 

 

 

-----------------------------------------------------------------------------------------------------------------------------------------------------------

1042 Shuffling Machine (20)(20 分)

Shuffling is a procedure used to randomize a deck of playing cards. Because standard shuffling techniques are seen as weak, and in order to avoid "inside jobs" where employees collaborate with gamblers by performing inadequate shuffles, many casinos employ automatic shuffling machines. Your task is to simulate a shuffling machine.

The machine shuffles a deck of 54 cards according to a given random order and repeats for a given number of times. It is assumed that the initial status of a card deck is in the following order:

S1, S2, ..., S13, H1, H2, ..., H13, C1, C2, ..., C13, D1, D2, ..., D13, J1, J2

where "S" stands for "Spade", "H" for "Heart", "C" for "Club", "D" for "Diamond", and "J" for "Joker". A given order is a permutation of distinct integers in [1, 54]. If the number at the i-th position is j, it means to move the card from position i to position j. For example, suppose we only have 5 cards: S3, H5, C1, D13 and J2. Given a shuffling order {4, 2, 5, 3, 1}, the result will be: J2, H5, D13, S3, C1. If we are to repeat the shuffling again, the result will be: C1, H5, S3, J2, D13.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer K (<= 20) which is the number of repeat times. Then the next line contains the given order. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the shuffling results in one line. All the cards are separated by a space, and there must be no extra space at the end of the line.

Sample Input:

2
36 52 37 38 3 39 40 53 54 41 11 12 13 42 43 44 2 4 23 24 25 26 27 6 7 8 48 49 50 51 9 10 14 15 16 5 17 18 19 1 20 21 22 28 29 30 31 32 33 34 35 45 46 47

Sample Output:

S7 C11 C10 C12 S1 H7 H8 H9 D8 D9 S11 S12 S13 D10 D11 D12 S3 S4 S6 S10 H1 H2 C13 D2 D3 D4 H6 H3 D13 J1 J2 C1 C2 C3 C4 D1 S5 H5 H11 H12 C6 C7 C8 C9 S2 S8 S9 H10 D5 D6 D7 H4 H13 C5

 

 

#include <bits/stdc++.h>

using namespace std;
char s[55][4]={"","S1","S2","S3","S4","S5","S6","S7","S8","S9","S10","S11","S12","S13",
                   "H1","H2","H3","H4","H5","H6","H7","H8","H9","H10","H11","H12","H13",
                   "C1","C2","C3","C4","C5","C6","C7","C8","C9","C10","C11","C12","C13",
                   "D1","D2","D3","D4","D5","D6","D7","D8","D9","D10","D11","D12","D13",
                   "J1","J2"};
int card[55][2], a[55];


int main(){
    int N, t = 0;
    cin >> N;
    for(int i = 1; i <= 54; i++) scanf("%d", &a[ card[i][0] = i]);
    while( N-- ){
       for(int i = 1; i <= 54; i++)
           card[ a[i] ][ t^1 ] = card[i][t];
       t ^= 1;
    }
    for(int i = 1; i <= 54; i++){
        if(i == 1) printf("%s", s[ card[i][t] ]);
        else printf(" %s", s[ card[i][t] ] );
    }
    return 0;
}

 

 

 

 

 

-----------------------------------------------------------------------------------------------------------------------------------------------------------

1043 Is It a Binary Search Tree (25)(25 分)

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
  • Both the left and right subtrees must also be binary search trees.

If we swap the left and right subtrees of every node, then the resulting tree is called the Mirror Image of a BST.

Now given a sequence of integer keys, you are supposed to tell if it is the preorder traversal sequence of a BST or the mirror image of a BST.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (<=1000). Then N integer keys are given in the next line. All the numbers in a line are separated by a space.

Output Specification:

For each test case, first print in a line "YES" if the sequence is the preorder traversal sequence of a BST or the mirror image of a BST, or "NO" if not. Then if the answer is "YES", print in the next line the postorder traversal sequence of that tree. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line.

Sample Input 1:

7
8 6 5 7 10 8 11

Sample Output 1:

YES
5 7 6 8 11 10 8

Sample Input 2:

7
8 10 11 8 6 7 5

Sample Output 2:

YES
11 8 10 7 5 6 8

Sample Input 3:

7
8 6 8 5 10 9 11

Sample Output 3:

NO
#include<bits/stdc++.h>
using namespace std;

int N;
vector< int > pre, in, post, post0;

bool postorder(int inl, int inr, int prel, int flag){
   if(inr < inl) return true;
   int i = inl;
   while( i <= inr && in[i] != pre[prel]) i++;
   if( i > inr ) return false;
   if( flag ){
      if( postorder(i+1, inr, prel+1, 1) && postorder(inl, i-1, inr-i+prel+1, 1) )   post0.push_back( in[i] );
      else return false;
   }
   else{
      if( postorder(inl, i-1, prel+1, 0) && postorder(i+1, inr, i-inl+1+prel, 0) )   post.push_back( in[i] );
      else return false;  
   }
   return true;
}

void print( vector<int> &ans ){
   printf("YES\n");
   for(int i = 0; i < N; i++)
      printf("%d%c", ans[i], (i == N-1) ? '\n' : ' ');
}

int main(){
   cin >> N;
   pre.resize(N);
   in.resize(N);
   for(int i = 0; i < N; i++) scanf("%d", &pre[i]);
   in = pre;
   sort( in.begin(), in.end() );
   if( postorder(0, N-1, 0, 0) ) print( post );
   else if( postorder(0, N-1, 0, 1) ) print( post0 );
   else printf("NO\n");
   return 0;
}

 

 

 

 

 

-----------------------------------------------------------------------------------------------------------------------------------------------------------

1044 Shopping in Mars (25)(25 分)

Shopping in Mars is quite a different experience. The Mars people pay by chained diamonds. Each diamond has a value (in Mars dollars M\$). When making the payment, the chain can be cut at any position for only once and some of the diamonds are taken off the chain one by one. Once a diamond is off the chain, it cannot be taken back. For example, if we have a chain of 8 diamonds with values M\$3, 2, 1, 5, 4, 6, 8, 7, and we must pay M\$15. We may have 3 options:

1. Cut the chain between 4 and 6, and take off the diamonds from the position 1 to 5 (with values 3+2+1+5+4=15).\

  1. Cut before 5 or after 6, and take off the diamonds from the position 4 to 6 (with values 5+4+6=15).\
  2. Cut before 8, and take off the diamonds from the position 7 to 8 (with values 8+7=15).\

Now given the chain of diamond values and the amount that a customer has to pay, you are supposed to list all the paying options for the customer.

If it is impossible to pay the exact amount, you must suggest solutions with minimum lost.

Input Specification:

Each input file contains one test case. For each case, the first line contains 2 numbers: N (<=10^5^), the total number of diamonds on the chain, and M (<=10^8^), the amount that the customer has to pay. Then the next line contains N positive numbers D~1~ ... D~N~ (D~i~<=10^3^ for all i=1, ..., N) which are the values of the diamonds. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print "i-j" in a line for each pair of i <= j such that D~i~ + ... + D~j~ = M. Note that if there are more than one solution, all the solutions must be printed in increasing order of i.

If there is no solution, output "i-j" for pairs of i <= j such that D~i~ + ... + D~j~ > M with (D~i~ + ... + D~j~ - M) minimized. Again all the solutions must be printed in increasing order of i.

It is guaranteed that the total value of diamonds is sufficient to pay the given amount.

Sample Input 1:

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

Sample Output 1:

1-5
4-6
7-8
11-11

Sample Input 2:

5 13
2 4 5 7 9

Sample Output 2:

2-4
4-5

 

 

#include <bits/stdc++.h>

using namespace std;
const int maxn = 1e5+10, inf = 99999999;
int a[maxn];
int N, S, p, q, sum, minS = inf;;
bool ok = false;

void simulation(int S){
   p = q = 1; sum = 0;
   while(q <= N){
      sum += a[q];
      if(sum > S) {
          minS = min(minS, sum);
          sum -= a[ p++ ]+a[ q-- ];
      }
      else if(sum == S){
         printf("%d-%d\n", p, q);
         sum -= a[p++];
         ok = true;
      }
      q++;
   }
}

int main(){
   cin >> N >> S;
   for(int i = 1; i <= N; i++) scanf("%d", &a[i]);
   simulation( S );
   if(!ok) simulation( minS );
   return 0;
}

 

 

 

 

 

 

-----------------------------------------------------------------------------------------------------------------------------------------------------------

1045 Favorite Color Stripe (30)(30 分)

Eva is trying to make her own color stripe out of a given one. She would like to keep only her favorite colors in her favorite order by cutting off those unwanted pieces and sewing the remaining parts together to form her favorite color stripe.

It is said that a normal human eye can distinguish about less than 200 different colors, so Eva's favorite colors are limited. However the original stripe could be very long, and Eva would like to have the remaining favorite stripe with the maximum length. So she needs your help to find her the best result.

Note that the solution might not be unique, but you only have to tell her the maximum length. For example, given a stripe of colors {2 2 4 1 5 5 6 3 1 1 5 6}. If Eva's favorite colors are given in her favorite order as {2 3 1 5 6}, then she has 4 possible best solutions {2 2 1 1 1 5 6}, {2 2 1 5 5 5 6}, {2 2 1 5 5 6 6}, and {2 2 3 1 1 5 6}.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (<=200) which is the total number of colors involved (and hence the colors are numbered from 1 to N). Then the next line starts with a positive integer M (<=200) followed by M Eva's favorite color numbers given in her favorite order. Finally the third line starts with a positive integer L (<=10000) which is the length of the given stripe, followed by L colors on the stripe. All the numbers in a line are separated by a space.

Output Specification:

For each test case, simply print in a line the maximum length of Eva's favorite stripe.

Sample Input:

6
5 2 3 1 5 6
12 2 2 4 1 5 5 6 3 1 1 5 6

Sample Output:

7

 

 

#include <bits/stdc++.h>
using namespace std;

const int maxa = 200+10, maxb = 1e4+10;
int N, t, a, b, A[maxa], B[maxb], P[maxb], ans = 0;

int main(){
   cin >> N;
   cin >> a;
   for(int i = 1; i <= a; i++) { scanf("%d", &t); A[t] = i; }
   cin >> b;
   for(int i = 1; i <= b; i++) scanf("%d", &B[i]);
   for(int i = 1; i <= b; i++){
      if( !A[ B[i] ] ) continue;
      for(int j = 0; j < i; j++) if( A[ B[j] ] <= A[ B[i] ] ){
          ans = max(ans, ( P[i] = max(P[i], P[j]+1) ) );
      }
   }
   cout << ans <<endl;
   return 0;
}

 

#include <cstdio>
#include <vector>
using namespace std;
int book[201], a[10001], dp[10001];
int main() {
    int n, m, x, l, num = 0, maxn = 1;
    scanf("%d %d", &n, &m);
    for(int i = 1; i <= m; i++) {
        scanf("%d", &x);
        book[x] = i;
    }
    scanf("%d", &l);
    for(int i = 0; i < l; i++) {
        scanf("%d", &x);
        if(book[x] >= 1)
            a[num++] = book[x];
    }
    for(int i = 0; i < num; i++) {
        dp[i] = 1;
        for(int j = 0; j < i; j++)
            if(a[i] >= a[j])
                maxn = max( dp[i] = max(dp[i], dp[j] + 1), maxn);
    }
    printf("%d", maxn);
    return 0;
}

 

 

 

 

 

 

-----------------------------------------------------------------------------------------------------------------------------------------------------------

1046 Shortest Distance (20)(20 分)

The task is really simple: given N exits on a highway which forms a simple cycle, you are supposed to tell the shortest distance between any pair of exits.

Input Specification:

Each input file contains one test case. For each case, the first line contains an integer N (in [3, 10^5^]), followed by N integer distances D~1~ D~2~ ... D~N~, where D~i~ is the distance between the i-th and the (i+1)-st exits, and D~N~ is between the N-th and the 1st exits. All the numbers in a line are separated by a space. The second line gives a positive integer M (<=10^4^), with M lines follow, each contains a pair of exit numbers, provided that the exits are numbered from 1 to N. It is guaranteed that the total round trip distance is no more than 10^7^.

Output Specification:

For each test case, print your results in M lines, each contains the shortest distance between the corresponding given pair of exits.

Sample Input:

5 1 2 4 14 9
3
1 3
2 5
4 1

Sample Output:

3
10
7

 

#include<bits/stdc++.h>
using namespace std;

const int maxn = 1e5+10;
int a[maxn], N;

int main(){
   cin >> N;
   for(int i = 1; i <= N; i++){
      scanf("%d", &a[i]);
      a[i] += a[i-1];
   }
   int A, B, sum = a[N];
   cin >> N;
   while(N--){
      scanf("%d%d", &A, &B);
      if(A > B) swap(A, B);
      cout << min( a[B-1]-a[A-1], sum - (a[B-1]-a[A-1]) ) << endl;
   }
   return 0;
}

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1047 Student List for Course (25)(25 分)

Zhejiang University has 40000 students and provides 2500 courses. Now given the registered course list of each student, you are supposed to output the student name lists of all the courses.

Input Specification:

Each input file contains one test case. For each case, the first line contains 2 numbers: N (<=40000), the total number of students, and K (<=2500), the total number of courses. Then N lines follow, each contains a student's name (3 capital English letters plus a one-digit number), a positive number C (<=20) which is the number of courses that this student has registered, and then followed by C course numbers. For the sake of simplicity, the courses are numbered from 1 to K.

Output Specification:

For each test case, print the student name lists of all the courses in increasing order of the course numbers. For each course, first print in one line the course number and the number of registered students, separated by a space. Then output the students' names in alphabetical order. Each name occupies a line.

Sample Input:

10 5
ZOE1 2 4 5
ANN0 3 5 2 1
BOB5 5 3 4 2 1 5
JOE4 1 2
JAY9 4 1 2 5 4
FRA8 3 4 2 5
DON2 2 4 5
AMY7 1 5
KAT3 3 5 4 2
LOR6 4 2 4 1 5

Sample Output:

1 4
ANN0
BOB5
JAY9
LOR6
2 7
ANN0
BOB5
FRA8
JAY9
JOE4
KAT3
LOR6
3 1
BOB5
4 7
BOB5
DON2
FRA8
JAY9
KAT3
LOR6
ZOE1
5 9
AMY7
ANN0
BOB5
DON2
FRA8
JAY9
KAT3
LOR6
ZOE1
#include<bits/stdc++.h>
using namespace std;

vector < vector< int > > v;
vector< int > Rank;
map<int, string> IDCache;

void getid(int i, char *name){
    int &t = Rank[i];
    for(int k = 0; k < 4; k++){
      if(k == 0) t = t*10+name[k]-'0';
      else t = t*26+name[k]-'A';
    }
   	string s = name;
   	IDCache[i] = s;
}

bool cmp(int a, int b){
	return Rank[a] < Rank[b];
}

int main(){
   int N, M;
   cin >> N >> M;
   v.resize(M+1);
   Rank.resize(N+1);
   for(int i = 0; i < N; i++){
   	  int n, x;
   	  char name[4];
      scanf("%s%d", name, &n);
      getid( i, name );
      while( n-- ){
      	 scanf("%d", &x);
      	 v[x].push_back( i );
      }
   }
   for(int i = 1; i <= M; i++){
   	   vector< int > &t = v[i];
   	   printf("%d %d\n", i, t.size());
   	   sort(t.begin(), t.end(), cmp);
   	   for(int i = 0; i < (int)t.size(); i++)
   	      printf("%s\n", IDCache[ t[i] ].c_str() );
   }
   return 0;
}

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1048 Find Coins (25)(25 分)

Eva loves to collect coins from all over the universe, including some other planets like Mars. One day she visited a universal shopping mall which could accept all kinds of coins as payments. However, there was a special requirement of the payment: for each bill, she could only use exactly two coins to pay the exact amount. Since she has as many as 10^5^ coins with her, she definitely needs your help. You are supposed to tell her, for any given amount of money, whether or not she can find two coins to pay for it.

Input Specification:

Each input file contains one test case. For each case, the first line contains 2 positive numbers: N (<=10^5^, the total number of coins) and M(<=10^3^, the amount of money Eva has to pay). The second line contains N face values of the coins, which are all positive numbers no more than 500. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the two face values V~1~ and V~2~ (separated by a space) such that V~1~ + V~2~ = M and V~1~ <= V~2~. If such a solution is not unique, output the one with the smallest V~1~. If there is no solution, output "No Solution" instead.

Sample Input 1:

8 15
1 2 8 7 2 4 11 15

Sample Output 1:

4 11

Sample Input 2:

7 14
1 8 7 2 4 11 15

Sample Output 2:

No Solution

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1e5;
vector< int > v;

int main(){
   int N ,S, a;
   cin >> N >> S;
   for(int i = 1; i <= N; i++){
      scanf("%d", &a);
      if( a < S ) v.push_back(a);
   }
   sort(v.begin(), v.end());
   int p = 0, q = v.size()-1;
   while(p < q){
      if(v[p] + v[q] == S){
         cout << v[p] << " " << v[q] <<endl;
         return 0;
      }
      else if(v[p] + v[q] > S) q--;
      else p++;
   }
   cout << "No Solution\n";
   return 0;
}
#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1e5;
map<int, int> Map;

int main(){
   int N ,S, a;
   cin >> N >> S;
   for(int i = 1; i <= N; i++){
      scanf("%d", &a);
      if( a >= S ) continue;
      Map[a]++;
   }
   for(auto &it : Map){
      int p = it.second;
      int q = Map[S - it.first];
      if(p && q && ((2*it.first == S)? (p >= 2): 1) ){
         cout << min(S - it.first, it.first) << " " << max(S - it.first, it.first) << endl;
         return 0;
      }
   }
   cout << "No Solution\n";
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1049 Counting Ones (30)(30 分)

The task is simple: given any positive integer N, you are supposed to count the total number of 1's in the decimal form of the integers from 1 to N. For example, given N being 12, there are five 1's in 1, 10, 11, and 12.

Input Specification:

Each input file contains one test case which gives the positive N (<=2^30^).

Output Specification:

For each test case, print the number of 1's in one line.

Sample Input:

12

Sample Output:

5

不是我的代码

#include<bits/stdc++.h>
using namespace std;

int main() {
    int n, left = 0, right = 0, a = 1, now = 1, ans = 0;
    scanf("%d", &n);
    while(n / a) {
        left = n / (a * 10), now = n / a % 10, right = n % a;
        if(now == 0) ans += left * a;
        else if(now == 1) ans += left * a + right + 1;
        else ans += (left + 1) * a;
        a *= 10;
    }
    printf("%d", ans);
    return 0;
}

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1050 String Subtraction (20)(20 分)

Given two strings S~1~ and S~2~, S = S~1~ - S~2~ is defined to be the remaining string after taking all the characters in S~2~ from S~1~. Your task is simply to calculate S~1~ - S~2~ for any given strings. However, it might not be that simple to do it fast.

Input Specification:

Each input file contains one test case. Each case consists of two lines which gives S~1~ and S~2~, respectively. The string lengths of both strings are no more than 10^4^. It is guaranteed that all the characters are visible ASCII codes and white space, and a new line character signals the end of a string.

Output Specification:

For each test case, print S~1~ - S~2~ in one line.

Sample Input:

They are students.
aeiou

Sample Output:

Thy r stdnts.

 

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 256;
int ASCII[MAXN];

int main(){
   string s, s1;
   getline(cin, s);
   getline(cin, s1);
   for(char &i : s1) ASCII[ int(i) ] = 1;
   for(char &i : s) if( !ASCII[ int(i) ] ){
      cout << char(i);
   }
   return 0;
}

 

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1051 Pop Sequence (25)(25 分)

Given a stack which can keep M numbers at most. Push N numbers in the order of 1, 2, 3, ..., N and pop randomly. You are supposed to tell if a given sequence of numbers is a possible pop sequence of the stack. For example, if M is 5 and N is 7, we can obtain 1, 2, 3, 4, 5, 6, 7 from the stack, but not 3, 2, 1, 7, 5, 6, 4.

Input Specification:

Each input file contains one test case. For each case, the first line contains 3 numbers (all no more than 1000): M (the maximum capacity of the stack), N (the length of push sequence), and K (the number of pop sequences to be checked). Then K lines follow, each contains a pop sequence of N numbers. All the numbers in a line are separated by a space.

Output Specification:

For each pop sequence, print in one line "YES" if it is indeed a possible pop sequence of the stack, or "NO" if not.

Sample Input:

5 7 5
1 2 3 4 5 6 7
3 2 1 7 5 6 4
7 6 5 4 3 2 1
5 6 4 3 7 2 1
1 7 6 5 4 3 2

Sample Output:

YES
NO
NO
YES
NO

 

 

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1000;
int sq[MAXN];

int main(){
   int M, N, K;
   cin >> M >> N >> K;
   while(K--){
      stack< int > S;
      for(int i = 1; i <= N; i++) scanf("%d", &sq[i]);
      int i = 1, j = 0;
      bool ok = false;
      while(1){
         if(!S.empty() && S.top() == sq[i]){
            S.pop();
            if(++i > N) {
                ok = true;
                break;
            }
         }
         else{
            S.push(++j);
            if((int)S.size() > M || j > N)  break;
         }
      }
      if(ok) cout << "YES\n";
      else cout << "NO\n";
   }
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1052 Linked List Sorting (25)(25 分)

A linked list consists of a series of structures, which are not necessarily adjacent in memory. We assume that each structure contains an integer key and a Next pointer to the next structure. Now given a linked list, you are supposed to sort the structures according to their key values in increasing order.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive N (< 10^5^) and an address of the head node, where N is the total number of nodes in memory and the address of a node is a 5-digit positive integer. NULL is represented by -1.

Then N lines follow, each describes a node in the format:

Address Key Next

where Address is the address of the node in memory, Key is an integer in [-10^5^, 10^5^], and Next is the address of the next node. It is guaranteed that all the keys are distinct and there is no cycle in the linked list starting from the head node.

Output Specification:

For each test case, the output format is the same as that of the input, where N is the total number of nodes in the list and all the nodes must be sorted order.

Sample Input:

5 00001
11111 100 -1
00001 0 22222
33333 100000 11111
12345 -1 33333
22222 1000 12345

Sample Output:

5 12345
12345 -1 00001
00001 0 11111
11111 100 22222
22222 1000 33333
33333 100000 -1

 

 

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 100000;
int N, head;
struct node{
   int pos, value, next;
   bool operator < (const node & rhs){
      return value < rhs.value;
   }
}Lnode[MAXN];

int main(){
   cin >> N >> head;
   node temp;
   for(int i = 0; i < N; i++){
      scanf("%d%d%d", &temp.pos, &temp.value, &temp.next);
      Lnode[temp.pos] =  temp;
   }
   vector< node > v;
   while(head != -1){
      v.push_back( Lnode[head] );
      head = Lnode[head].next;
   }
   sort(v.begin(), v.end());
   int Size = v.size();
   if( !Size ) {printf("0 -1\n"); return 0;}
   printf("%d %05d\n", Size, v[0].pos);
   for(int i = 0; i < Size; i++){
      if(i != Size-1) printf("%05d %d %05d\n", v[i].pos, v[i].value, v[i+1].pos);
      else printf("%05d %d -1\n", v[i].pos, v[i].value);

   }
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1053 Path of Equal Weight (30)(30 分)

Given a non-empty tree with root R, and with weight W~i~ assigned to each tree node T~i~. The weight of a path from R to L is defined to be the sum of the weights of all the nodes along the path from R to any leaf node L.

Now given any weighted tree, you are supposed to find all the paths with their weights equal to a given number. For example, let's consider the tree showed in Figure 1: for each node, the upper number is the node ID which is a two-digit number, and the lower number is the weight of that node. Suppose that the given number is 24, then there exists 4 different paths which have the same given weight: {10 5 2 7}, {10 4 10}, {10 3 3 6 2} and {10 3 3 6 2}, which correspond to the red edges in Figure 1.

\ Figure 1

Input Specification:

Each input file contains one test case. Each case starts with a line containing 0 < N <= 100, the number of nodes in a tree, M (< N), the number of non-leaf nodes, and 0 < S < 2^30^, the given weight number. The next line contains N positive numbers where W~i~ (&lt1000) corresponds to the tree node T~i~. Then M lines follow, each in the format:

ID K ID[1] ID[2] ... ID[K]

where ID is a two-digit number representing a given non-leaf node, K is the number of its children, followed by a sequence of two-digit ID's of its children. For the sake of simplicity, let us fix the root ID to be 00.

Output Specification:

For each test case, print all the paths with weight S in non-increasing order. Each path occupies a line with printed weights from the root to the leaf in order. All the numbers must be separated by a space with no extra space at the end of the line.

Note: sequence {A~1~, A~2~, ..., A~n~} is said to be greater than sequence {B~1~, B~2~, ..., B~m~} if there exists 1 <= k < min{n, m} such that A~i~ = B~i~ for i=1, ... k, and A~k+1~ > B~k+1~.

Sample Input:

20 9 24
10 2 4 3 5 10 2 18 9 7 2 2 1 3 12 1 8 6 2 2
00 4 01 02 03 04
02 1 05
04 2 06 07
03 3 11 12 13
06 1 09
07 2 08 10
16 1 15
13 3 14 16 17
17 2 18 19

Sample Output:

10 5 2 7
10 4 10
10 3 3 6 2
10 3 3 6 2

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 100000;
int N, K, S;
vector< vector<int> >v;
vector< int > ans, w;

bool cmp(int lhs, int rhs){
   return w[lhs] > w[rhs];
}

void print(){
    for(int i = 0; i < (int)ans.size(); i++)
        printf("%d%c", ans[i], (i == (int)ans.size()-1) ? '\n': ' ');
}

void dfs(int i, int sum){
   int Size = v[i].size();
   if( !Size ){
      if(sum == S) print();
      return;
   }
   for(auto j : v[i]){
      ans.push_back( w[j] );
      dfs(j, sum + w[j]);
      ans.pop_back();
   }
}

int main(){
   cin >> N >> K >> S;
   v.resize(N);
   w.resize(N);
   for(int i = 0; i < N; i++) scanf("%d", &w[i]);
   while(K--){
      int id, M, x;
      cin >> id >> M;
      while(M--){
         scanf("%d", &x);
         v[id].push_back(x);
      }
      sort(v[id].begin(), v[id].end(), cmp);
   }
   ans.push_back( w[0] );
   dfs(0, w[0]);
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1054 The Dominant Color (20)(20 分)

Behind the scenes in the computer's memory, color is always talked about as a series of 24 bits of information for each pixel. In an image, the color with the largest proportional area is called the dominant color. A strictly dominant color takes more than half of the total area. Now given an image of resolution M by N (for example, 800x600), you are supposed to point out the strictly dominant color.

Input Specification:

Each input file contains one test case. For each case, the first line contains 2 positive numbers: M (<=800) and N (<=600) which are the resolutions of the image. Then N lines follow, each contains M digital colors in the range [0, 2^24^). It is guaranteed that the strictly dominant color exists for each input image. All the numbers in a line are separated by a space.

Output Specification:

For each test case, simply print the dominant color in a line.

Sample Input:

5 3
0 0 255 16777215 24
24 24 0 0 24
24 0 24 24 24

Sample Output:

24

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1e8;
int N, M, x;
int a[MAXN];

int main(){
   cin >> N >> M;
   N *= M;
   M = N/2;
   while(N--){
      scanf("%d", &x);
      if(++a[x] > M){
         cout << x <<endl;
         break;
      }
   }
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1055 The World's Richest(25 分)

Forbes magazine publishes every year its list of billionaires based on the annual ranking of the world's wealthiest people. Now you are supposed to simulate this job, but concentrate only on the people in a certain range of ages. That is, given the net worths of N people, you must find the M richest people in a given range of their ages.

Input Specification:

Each input file contains one test case. For each case, the first line contains 2 positive integers: N (≤10​5​​) - the total number of people, and K (≤10​3​​) - the number of queries. Then N lines follow, each contains the name (string of no more than 8 characters without space), age (integer in (0, 200]), and the net worth (integer in [−10​6​​,10​6​​]) of a person. Finally there are K lines of queries, each contains three positive integers: M (≤100) - the maximum number of outputs, and [Amin, Amax] which are the range of ages. All the numbers in a line are separated by a space.

Output Specification:

For each query, first print in a line Case #X: where X is the query number starting from 1. Then output the M richest people with their ages in the range [Amin, Amax]. Each person's information occupies a line, in the format

Name Age Net_Worth

The outputs must be in non-increasing order of the net worths. In case there are equal worths, it must be in non-decreasing order of the ages. If both worths and ages are the same, then the output must be in non-decreasing alphabetical order of the names. It is guaranteed that there is no two persons share all the same of the three pieces of information. In case no one is found, output None.

Sample Input:

12 4
Zoe_Bill 35 2333
Bob_Volk 24 5888
Anny_Cin 95 999999
Williams 30 -22
Cindy 76 76000
Alice 18 88888
Joe_Mike 32 3222
Michael 5 300000
Rosemary 40 5888
Dobby 24 5888
Billy 24 5888
Nobody 5 0
4 15 45
4 30 35
4 5 95
1 45 50

Sample Output:

Case #1:
Alice 18 88888
Billy 24 5888
Bob_Volk 24 5888
Dobby 24 5888
Case #2:
Joe_Mike 32 3222
Zoe_Bill 35 2333
Williams 30 -22
Case #3:
Anny_Cin 95 999999
Michael 5 300000
Alice 18 88888
Cindy 76 76000
Case #4:
None
#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1e5+10;

struct node{
   char Name[10];
   int Age, Worth;
   bool operator < (const node &rhs) const {
      if(Worth != rhs.Worth) return Worth > rhs.Worth;
      if(Age != rhs.Age) return Age < rhs.Age;
      return strcmp(Name, rhs.Name) < 0;
   }
};
vector< node > v;

int main(){
   int N, Q;
   cin >> N >> Q;
   v.resize(N);
   for(int i = 0; i < N; i++){
   	  char Name[10];
   	  int Age, Worth;
   	  scanf("%s%d%d", v[i].Name, &v[i].Age, &v[i].Worth);
   }
   sort( v.begin(), v.end() );
   for(int k = 1; k <= Q; k++){
      int n, Amin, Amax, cnt= 0;
      scanf("%d %d %d", &n, &Amin, &Amax);
      printf("Case #%d:\n", k); 
      for(int i = 0; i < N; i++){
         if( v[i].Age >= Amin && v[i].Age <= Amax ){
	     printf("%s %d %d\n", v[i].Name, v[i].Age, v[i].Worth);
             if(++cnt == n) break;
	 }      
      }
      if( !cnt ) printf("None\n");
   }
   return 0;
}

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1056 Mice and Rice (25)(25 分)

Mice and Rice is the name of a programming contest in which each programmer must write a piece of code to control the movements of a mouse in a given map. The goal of each mouse is to eat as much rice as possible in order to become a FatMouse.

First the playing order is randomly decided for N~P~ programmers. Then every N~G~ programmers are grouped in a match. The fattest mouse in a group wins and enters the next turn. All the losers in this turn are ranked the same. Every N~G~ winners are then grouped in the next match until a final winner is determined.

For the sake of simplicity, assume that the weight of each mouse is fixed once the programmer submits his/her code. Given the weights of all the mice and the initial playing order, you are supposed to output the ranks for the programmers.

Input Specification:

Each input file contains one test case. For each case, the first line contains 2 positive integers: N~P~ and N~G~ (<= 1000), the number of programmers and the maximum number of mice in a group, respectively. If there are less than N~G~ mice at the end of the player's list, then all the mice left will be put into the last group. The second line contains N~P~ distinct non-negative numbers W~i~ (i=0,...N~P~-1) where each W~i~ is the weight of the i-th mouse respectively. The third line gives the initial playing order which is a permutation of 0,...N~P~-1 (assume that the programmers are numbered from 0 to N~P~-1). All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the final ranks in a line. The i-th number is the rank of the i-th programmer, and all the numbers must be separated by a space, with no extra space at the end of the line.

Sample Input:

11 3
25 18 0 46 37 3 19 22 57 56 10
6 0 8 7 10 5 9 1 4 2 3

Sample Output:

5 5 5 2 5 5 5 3 1 3 5
#include<bits/stdc++.h>
using namespace std;

int main(){
   int NG, NP;
   cin >> NG >> NP;
   queue< int > Q;
   vector< int > v(NG), Rank(NG);
   for(int i = 0; i < NG; i++) scanf("%d", &v[i]);
   for(int i = 0; i < NG; i++) {
      int x;
      scanf("%d", &x);
      Q.push(x);
   }
   while( !Q.empty() ){
      int Size = Q.size();
      int k = 1+ceil( Size*1.0/NP );
      while( Size ){
      	 int maxn = -1, index;
         for(int i = 0; i < NP && Size > 0; i++, Size--){
            int t = Q.front(); Q.pop();
            Rank[t] = k;
            if( v[t] > maxn ) maxn = v[ index = t ];
         }
         Q.push( index );
      } 
	  if( Q.size() == 1 ) {
	     Rank[ Q.front() ] = 1;
		 break;
      }  
   }
   for(int i = 0; i < NG; i++)
      printf("%d%c", Rank[i], (i == NG-1 ? '\n' : ' ') );
   return 0;
}

 

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1057 Stack (30)(30 分)

Stack is one of the most fundamental data structures, which is based on the principle of Last In First Out (LIFO). The basic operations include Push (inserting an element onto the top position) and Pop (deleting the top element). Now you are supposed to implement a stack with an extra operation: PeekMedian -- return the median value of all the elements in the stack. With N elements, the median value is defined to be the (N/2)-th smallest element if N is even, or ((N+1)/2)-th if N is odd.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (<= 10^5^). Then N lines follow, each contains a command in one of the following 3 formats:

Push key\ Pop\ PeekMedian

where key is a positive integer no more than 10^5^.

Output Specification:

For each Push command, insert key into the stack and output nothing. For each Pop or PeekMedian command, print in a line the corresponding returned value. If the command is invalid, print "Invalid" instead.

Sample Input:

17
Pop
PeekMedian
Push 3
PeekMedian
Push 2
PeekMedian
Push 1
PeekMedian
Pop
Pop
Push 5
Push 4
PeekMedian
Pop
Pop
Pop
Pop

Sample Output:

Invalid
Invalid
3
2
2
1
2
4
4
5
3
Invalid

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1058 A+B in Hogwarts (20)(20 分)

If you are a fan of Harry Potter, you would know the world of magic has its own currency system -- as Hagrid explained it to Harry, "Seventeen silver Sickles to a Galleon and twenty-nine Knuts to a Sickle, it's easy enough." Your job is to write a program to compute A+B where A and B are given in the standard form of "Galleon.Sickle.Knut" (Galleon is an integer in [0, 10^7^], Sickle is an integer in [0, 17), and Knut is an integer in [0, 29)).

Input Specification:

Each input file contains one test case which occupies a line with A and B in the standard form, separated by one space.

Output Specification:

For each test case you should output the sum of A and B in one line, with the same format as the input.

Sample Input:

3.2.1 10.16.27

Sample Output:

14.1.28

 

#include<bits/stdc++.h>
using namespace std;

int main(){
   int a, b, c, a1, b1, c1, B, A;
   scanf("%d.%d.%d %d.%d.%d", &a, &b, &c, &a1, &b1, &c1);
   B = (c + c1) / 29;
   c = (c + c1) % 29;
   A = (b + b1 + B) / 17;
   b = (b + b1 + B) % 17;
   a = a + a1 + A;
   printf("%d.%d.%d\n", a, b, c);
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1059 Prime Factors (25)(25 分)

Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N = p~1~\^k~1~ * p~2~\^k~2~ *…*p~m~\^k~m~.

Input Specification:

Each input file contains one test case which gives a positive integer N in the range of long int.

Output Specification:

Factor N in the format N = p~1~\^k~1~ * p~2~\^k~2~ *…*p~m~\^k~m~, where p~i~'s are prime factors of N in increasing order, and the exponent k~i~ is the number of p~i~ -- hence when there is only one p~i~, k~i~ is 1 and must NOT be printed out.

Sample Input:

97532468

Sample Output:

97532468=2^2*11*17*101*1291

 

 

#include<bits/stdc++.h>
using namespace std;

typedef long long LL;
LL N;
int flag = 1;

bool isprime(LL n){
   if(n == 1) return false;
   for(LL i = 2; i <= sqrt(n)+0.5; i++ ){
      if(n % i == 0) return false;
   }
   return true;
}

void print(LL i, int cnt){
  if(flag) flag = 0;
  else cout << '*';
  cout << i;
  if(cnt != 1) cout << '^' <<cnt;
}

int main(){
   cin >> N;
   cout << N << '=';
   if(N == 1) {
      cout << "1\n";
      return 0;
   }
   for(LL i = 2; N != 1; i++){
      if( N % i == 0 && isprime(i) ){
         int cnt = 0;
         while(N % i == 0){
            N /= i;
            cnt++;
         }
         print(i, cnt);
      }
   }
   return 0;
}

 

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1060 Are They Equal (25)(25 分)

If a machine can save only 3 significant digits, the float numbers 12300 and 12358.9 are considered equal since they are both saved as 0.123*10^5^ with simple chopping. Now given the number of significant digits on a machine and two float numbers, you are supposed to tell if they are treated equal in that machine.

Input Specification:

Each input file contains one test case which gives three numbers N, A and B, where N (<100) is the number of significant digits, and A and B are the two float numbers to be compared. Each float number is non-negative, no greater than 10^100^, and that its total digit number is less than 100.

Output Specification:

For each test case, print in a line "YES" if the two numbers are treated equal, and then the number in the standard form "0.d~1~...d~N~*10\^k" (d~1~>0 unless the number is 0); or "NO" if they are not treated equal, and then the two numbers in their standard form. All the terms must be separated by a space, with no extra space at the end of a line.

Note: Simple chopping is assumed without rounding.

Sample Input 1:

3 12300 12358.9

Sample Output 1:

YES 0.123*10^5

Sample Input 2:

3 120 128

Sample Output 2:

NO 0.120*10^3 0.128*10^3

 

 

#include<bits/stdc++.h>
using namespace std;

int N;
string a, b, s1 = "0.", s2 = "0.";
int p1 = 0,p2 = 0, q1 = 0, q2 = 0;

void f(string &a, string &s1, int &p1, int &q1){
    while( p1 < a.length() && a[p1] != '.') p1++;
    while( q1 < a.length() && ( a[q1] == '0' || a[q1]=='.') ) q1++;
    for(int i = 0,j = q1; i < N; i++){
      if(j >= a.length() ) s1 += '0';
      else if(j == p1) { s1 += a[++j]; j++; }
      else s1 += a[j++];
    }
}

int main(){
   cin >> N >> a >> b;
   f(a, s1, p1, q1);
   f(b, s2, p2, q2);
   if(s1 == s2) cout << "YES " << s1 << "*10^" << ( p1-q1 < 0 ? p1-q1+1 :p1-q1 ) << endl;
   else cout << "NO " << s1 << "*10^" << ( p1-q1 < 0 ? p1-q1+1 : p1-q1 ) << " " << s2 << "*10^" << ( p2-q2 < 0 ? p2-q2+1 : p2-q2) << endl;
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1061 Dating (20)(20 分)

Sherlock Holmes received a note with some strange strings: "Let's date! 3485djDkxh4hhGE 2984akDfkkkkggEdsb s&hgsfdk d&Hyscvnm". It took him only a minute to figure out that those strange strings are actually referring to the coded time "Thursday 14:04" -- since the first common capital English letter (case sensitive) shared by the first two strings is the 4th capital letter 'D', representing the 4th day in a week; the second common character is the 5th capital letter 'E', representing the 14th hour (hence the hours from 0 to 23 in a day are represented by the numbers from 0 to 9 and the capital letters from A to N, respectively); and the English letter shared by the last two strings is 's' at the 4th position, representing the 4th minute. Now given two pairs of strings, you are supposed to help Sherlock decode the dating time.

Input Specification:

Each input file contains one test case. Each case gives 4 non-empty strings of no more than 60 characters without white space in 4 lines.

Output Specification:

For each test case, print the decoded time in one line, in the format "DAY HH:MM", where "DAY" is a 3-character abbreviation for the days in a week -- that is, "MON" for Monday, "TUE" for Tuesday, "WED" for Wednesday, "THU" for Thursday, "FRI" for Friday, "SAT" for Saturday, and "SUN" for Sunday. It is guaranteed that the result is unique for each case.

Sample Input:

3485djDkxh4hhGE 
2984akDfkkkkggEdsb 
s&hgsfdk 
d&Hyscvnm

Sample Output:

THU 14:04

 

 

#include<bits/stdc++.h>
using namespace std;

const char *Data[7] = { "MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"};
int main(){
   int flag = 1;
   string a, b;
   cin >> a >> b;
   for(int i = 0;; i++){
      if( flag && isupper(a[i]) && a[i] == b[i] && a[i] <= 'G' ) {
         cout << Data[ (int)(a[i]-'A') ] << " ";
         flag = 0;
      }
      else if( !flag && a[i] == b[i] && ( isdigit( a[i] ) || (a[i] >= 'A' && a[i] <= 'N') ) ){
         printf("%02d:", ( isupper(a[i]) ? (a[i]-'A'+10) : (a[i]-'0') ) );
         break;
      }
   }
   cin >> a >> b;
   for(int i = 0;; i++) if( isalpha(a[i]) && a[i] == b[i] ){
      printf("%02d\n", i);
      break;
   }
   return 0;
}

 

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1062 Talent and Virtue (25)(25 分)

About 900 years ago, a Chinese philosopher Sima Guang wrote a history book in which he talked about people's talent and virtue. According to his theory, a man being outstanding in both talent and virtue must be a "sage(圣人)"; being less excellent but with one's virtue outweighs talent can be called a "nobleman(君子)"; being good in neither is a "fool man(愚人)"; yet a fool man is better than a "small man(小人)" who prefers talent than virtue.

Now given the grades of talent and virtue of a group of people, you are supposed to rank them according to Sima Guang's theory.

Input Specification:

Each input file contains one test case. Each case first gives 3 positive integers in a line: N (<=10^5^), the total number of people to be ranked; L (>=60), the lower bound of the qualified grades -- that is, only the ones whose grades of talent and virtue are both not below this line will be ranked; and H (<100), the higher line of qualification -- that is, those with both grades not below this line are considered as the "sages", and will be ranked in non-increasing order according to their total grades. Those with talent grades below H but virtue grades not are cosidered as the "noblemen", and are also ranked in non-increasing order according to their total grades, but they are listed after the "sages". Those with both grades below H, but with virtue not lower than talent are considered as the "fool men". They are ranked in the same way but after the "noblemen". The rest of people whose grades both pass the L line are ranked after the "fool men".

Then N lines follow, each gives the information of a person in the format:

ID_Number Virtue_Grade Talent_Grade

where ID_Number is an 8-digit number, and both grades are integers in [0, 100]. All the numbers are separated by a space.

Output Specification:

The first line of output must give M (<=N), the total number of people that are actually ranked. Then M lines follow, each gives the information of a person in the same format as the input, according to the ranking rules. If there is a tie of the total grade, they must be ranked with respect to their virtue grades in non-increasing order. If there is still a tie, then output in increasing order of their ID's.

Sample Input:

14 60 80
10000001 64 90
10000002 90 60
10000011 85 80
10000003 85 80
10000004 80 85
10000005 82 77
10000006 83 76
10000007 90 78
10000008 75 79
10000009 59 90
10000010 88 45
10000012 80 100
10000013 90 99
10000014 66 60

Sample Output:

12
10000013 90 99
10000012 80 100
10000003 85 80
10000011 85 80
10000004 80 85
10000007 90 78
10000006 83 76
10000005 82 77
10000002 90 60
10000014 66 60
10000008 75 79
10000001 64 90

 

 

 

#include<bits/stdc++.h>
using namespace std;

int N, L, H;
struct node{
   int id, V, T, grade;
   bool operator < (const node &rhs) const{
      if(grade != rhs.grade) return grade > rhs.grade;
      else if( V != rhs.V ) return V > rhs.V;
      else return id < rhs.id;
   }
}temp;
vector< node > v[4];

int main(){
   cin >> N >> L >> H;
   for(int i = 0; i < N; i++){
      scanf("%d%d%d", &temp.id, &temp.V, &temp.T);
      temp.grade = temp.V + temp.T;
      if(temp.V >= H && temp.T >= H) v[0].push_back( temp );
      else if(temp.V >= H && temp.T >= L) v[1].push_back( temp );
      else if(temp.V >= L && temp.T >= L && temp.V >= temp.T) v[2].push_back( temp );
      else if(temp.V >= L && temp.T >= L) v[3].push_back( temp );
   }
   for(int i = 0; i < 4; i++) sort( v[i].begin(), v[i].end() );
   printf("%d\n", v[0].size() + v[1].size() + v[2].size() + v[3].size() );
   for(int i = 0; i < 4; i++){
      for(auto &it : v[i])
         printf("%08d %d %d\n", it.id, it.V, it.T);
   }
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1063 Set Similarity (25)(25 分)

Given two sets of integers, the similarity of the sets is defined to be N~c~/N~t~*100%, where N~c~ is the number of distinct common numbers shared by the two sets, and N~t~ is the total number of distinct numbers in the two sets. Your job is to calculate the similarity of any given pair of sets.

Input Specification:

Each input file contains one test case. Each case first gives a positive integer N (<=50) which is the total number of sets. Then N lines follow, each gives a set with a positive M (<=10^4^) and followed by M integers in the range [0, 10^9^]. After the input of sets, a positive integer K (<=2000) is given, followed by K lines of queries. Each query gives a pair of set numbers (the sets are numbered from 1 to N). All the numbers in a line are separated by a space.

Output Specification:

For each query, print in one line the similarity of the sets, in the percentage form accurate up to 1 decimal place.

Sample Input:

3
3 99 87 101
4 87 101 5 87
7 99 101 18 5 135 18 99
2
1 2
1 3

Sample Output:

50.0%
33.3%

 

 

 

#include<bits/stdc++.h>
using namespace std;

int N, M, x, y, nc, nt;
vector< set< int > > v;

int main(){
    cin >> N;
    v.resize( N+1 );
    for(int i = 1; i <= N; i++){
       cin >> M;
       while( M-- ){
          scanf("%d", &x);
          v[i].insert( x );
       }
    }
    cin >> M;
    while( M-- ){
       scanf("%d%d", &x, &y);
       nc = 0, nt = v[y].size();
       for(auto it : v[x]) {
            if( v[y].find(it) == v[y].end() ) nt++;
            else nc++;
       }
       printf("%.1f%\n", nc*100.0/nt);
    }
    return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1064 Complete Binary Search Tree (30)(30 分)

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
  • Both the left and right subtrees must also be binary search trees.

A Complete Binary Tree (CBT) is a tree that is completely filled, with the possible exception of the bottom level, which is filled from left to right.

Now given a sequence of distinct non-negative integer keys, a unique BST can be constructed if it is required that the tree must also be a CBT. You are supposed to output the level order traversal sequence of this BST.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (<=1000). Then N distinct non-negative integer keys are given in the next line. All the numbers in a line are separated by a space and are no greater than 2000.

Output Specification:

For each test case, print in one line the level order traversal sequence of the corresponding complete binary search tree. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line.

Sample Input:

10
1 2 3 4 5 6 7 8 9 0

Sample Output:

6 3 8 1 5 7 9 0 2 4
#include<bits/stdc++.h>
using namespace std;

int N;
vector< int > pre;
vector< vector< int > > H(15);

int Log2(int x){
	return log(x)/log(2)-0.00005;
}


int LeftNum(int N){
   	int h = Log2(N+1)+1;
  	int n = pow(2, h-2)-1+0.5;
  	int Left = N - 2*n - 1;
  	return n+min(Left, (int)(pow(2, h-2)+0.5) );
}

void levelorder(int prel, int prer, int height){
	if(prer < prel) return;
	int n = prer-prel+1, L = LeftNum(n), R = n-L;
	H[height].push_back( pre[prel+L] );
	levelorder(prel, prel+L-1, height+1);
	levelorder(prel+L+1,prer, height+1);
}

void print(){
   int cnt = 0, i = 0;
   do{
   	  for(auto &j : H[i]){
   	  	 printf("%d", j);
   	  	 if(++cnt == N) return;
   	  	 else putchar(' ');
      }
  }while(++i);
}

int main(){
   cin >> N;
   pre.resize(N);
   for(int i = 0; i < N; i++) scanf("%d", &pre[i]);
   sort(pre.begin(), pre.end() );
   levelorder(0, N-1, 0);
   print();
   return 0;
}

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1065 A+B and C (64bit) (20)(20 分)

Given three integers A, B and C in [-2^63^, 2^63^], you are supposed to tell whether A+B > C.

Input Specification:

The first line of the input gives the positive number of test cases, T (<=10). Then T test cases follow, each consists of a single line containing three integers A, B and C, separated by single spaces.

Output Specification:

For each test case, output in one line "Case #X: true" if A+B&gtC, or "Case #X: false" otherwise, where X is the case number (starting from 1).

Sample Input:

3
1 2 3
2 3 4
9223372036854775807 -9223372036854775808 0

Sample Output:

Case #1: false
Case #2: true
Case #3: false

 

#include<bits/stdc++.h>
using namespace std;

int N;
long long a, b, c, sum;

int main(){
    cin >> N;
    for(int i = 1; i <= N; i++){
        bool ok;
        cout << "Case #" << i << ": ";
        cin >> a >> b >> c;
        sum = a + b;
        if( a > 0 && b > 0 && sum <= 0 ) ok = true;
        else if( a < 0 && b < 0 && sum >=0 ) ok = false;
        else if( sum > c ) ok = true;
        else ok = false;
        
        if(ok) cout << "true\n";
        else cout << "false\n";
    }
    return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1066 Root of AVL Tree (25)(25 分)

An AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. Figures 1-4 illustrate the rotation rules.

Now given a sequence of insertions, you are supposed to tell the root of the resulting AVL tree.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (<=20) which is the total number of keys to be inserted. Then N distinct integer keys are given in the next line. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the root of the resulting AVL tree in one line.

Sample Input 1:

5
88 70 61 96 120

Sample Output 1:

70

Sample Input 2:

7
88 70 61 96 120 90 65

Sample Output 2:

88
#include<bits/stdc++.h>
using namespace std;

typedef struct node{
   int v;
   struct node *L, *R;
} *Tree;


Tree RR( Tree &T ){
   Tree temp = T->L;
   T->L = temp->R;
   temp->R = T;
   return temp;
}

Tree LL( Tree &T ){
   Tree temp = T->R;
   T->R = temp->L;
   temp->L = T;
   return temp;
}

int GetNum( Tree T ){
   if( T == NULL ) return 0;
   else return 1+max( GetNum(T->L) , GetNum(T->R) ); 
}

void build(Tree &T, int x){
   if( T == NULL ){
   	  T = new struct node();
      T->R = T->L = NULL;
      T->v = x;
   }
   else if( T->v > x ){
      build(T->L, x);
      if( GetNum(T->L)-GetNum(T->R) >= 2 ){
         if( T->L->v < x) T->L = LL(T->L);
         T = RR(T);
      }
   }
   else if( T->v < x ){
      build(T->R, x);
      if( GetNum(T->R)-GetNum(T->L) >= 2 ){
         if( T->R->v > x) T->R = RR(T->R);
         T = LL(T);
      }
   }
}

int main(){
   int N, x;
   cin >> N;
   Tree T = NULL;
   for(int i = 0; i < N; i++){
      cin >> x;
      build(T, x);
   }
   cout << T->v << endl;
   return 0;
}

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1067 Sort with Swap(0,*) (25)(25 分)

Given any permutation of the numbers {0, 1, 2,..., N-1}, it is easy to sort them in increasing order. But what if Swap(0, *) is the ONLY operation that is allowed to use? For example, to sort {4, 0, 2, 1, 3} we may apply the swap operations in the following way:

Swap(0, 1) => {4, 1, 2, 0, 3}\ Swap(0, 3) => {4, 1, 2, 3, 0}\ Swap(0, 4) => {0, 1, 2, 3, 4}

Now you are asked to find the minimum number of swaps need to sort the given permutation of the first N nonnegative integers.

Input Specification:

Each input file contains one test case, which gives a positive N (<=10^5^) followed by a permutation sequence of {0, 1, ..., N-1}. All the numbers in a line are separated by a space.

Output Specification:

For each case, simply print in a line the minimum number of swaps need to sort the given permutation.

Sample Input:

10 3 5 7 2 6 4 9 0 8 1

Sample Output:

9

 

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1e5 + 10;

int fd[MAXN];
bool visit[MAXN];

int main(){
   int N, sum = 0;
   cin>>N;
   for(int i = 0; i < N; i++) scanf("%d", &fd[i]);
   for(int i = 0; i < N; i++){
     if( !visit[i] ){
        int root = i, cnt = 0;
        do{
            visit[i] = true;
            i = fd[i];
            cnt++;
        }while(i != root);
        if( cnt == 1) ;
        else if( !i ) sum += cnt - 1;
        else sum += cnt + 1;
     }
  }
  cout << sum << endl;
  return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1068 Find More Coins (30)(30 分)

Eva loves to collect coins from all over the universe, including some other planets like Mars. One day she visited a universal shopping mall which could accept all kinds of coins as payments. However, there was a special requirement of the payment: for each bill, she must pay the exact amount. Since she has as many as 10^4^ coins with her, she definitely needs your help. You are supposed to tell her, for any given amount of money, whether or not she can find some coins to pay for it.

Input Specification:

Each input file contains one test case. For each case, the first line contains 2 positive numbers: N (<=10^4^, the total number of coins) and M(<=10^2^, the amount of money Eva has to pay). The second line contains N face values of the coins, which are all positive numbers. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the face values V~1~ <= V~2~ <= ... <= V~k~ such that V~1~ + V~2~ + ... + V~k~ = M. All the numbers must be separated by a space, and there must be no extra space at the end of the line. If such a solution is not unique, output the smallest sequence. If there is no solution, output "No Solution" instead.

Note: sequence {A[1], A[2], ...} is said to be "smaller" than sequence {B[1], B[2], ...} if there exists k >= 1 such that A[i]=B[i] for all i < k, and A[k] < B[k].

Sample Input 1:

8 9
5 9 8 7 2 3 4 1

Sample Output 1:

1 3 5

Sample Input 2:

4 8
7 2 4 3

Sample Output 2:

No Solution

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1069 The Black Hole of Numbers (20)(20 分)

For any 4-digit integer except the ones with all the digits being the same, if we sort the digits in non-increasing order first, and then in non-decreasing order, a new number can be obtained by taking the second number from the first one. Repeat in this manner we will soon end up at the number 6174 -- the "black hole" of 4-digit numbers. This number is named Kaprekar Constant.

For example, start from 6767, we'll get:

7766 - 6677 = 1089\ 9810 - 0189 = 9621\ 9621 - 1269 = 8352\ 8532 - 2358 = 6174\ 7641 - 1467 = 6174\ ... ...

Given any 4-digit number, you are supposed to illustrate the way it gets into the black hole.

Input Specification:

Each input file contains one test case which gives a positive integer N in the range (0, 10000).

Output Specification:

If all the 4 digits of N are the same, print in one line the equation "N

  • N = 0000". Else print each step of calculation in a line until 6174 comes out as the difference. All the numbers must be printed as 4-digit numbers.

Sample Input 1:

6767

Sample Output 1:

7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174

Sample Input 2:

2222

Sample Output 2:

2222 - 2222 = 0000

 

 

#include<bits/stdc++.h>
using namespace std;


int main(){
   int c;
   string a, b;
   cin >> c;
   do{
      a = to_string(c);
      while(a.length() < 4) a += '0';
      sort( a.begin(), a.end() );
      b = a;
      reverse( b.begin(), b.end() );
      c = stoi(b) - stoi(a);
      printf("%04d - %04d = %04d\n", stoi(b), stoi(a), c);
   }while( c != 0 && c != 6174);
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1070 Mooncake (25)(25 分)

Mooncake is a Chinese bakery product traditionally eaten during the Mid-Autumn Festival. Many types of fillings and crusts can be found in traditional mooncakes according to the region's culture. Now given the inventory amounts and the prices of all kinds of the mooncakes, together with the maximum total demand of the market, you are supposed to tell the maximum profit that can be made.

Note: partial inventory storage can be taken. The sample shows the following situation: given three kinds of mooncakes with inventory amounts being 180, 150, and 100 thousand tons, and the prices being 7.5, 7.2, and 4.5 billion yuans. If the market demand can be at most 200 thousand tons, the best we can do is to sell 150 thousand tons of the second kind of mooncake, and 50 thousand tons of the third kind. Hence the total profit is 7.2 + 4.5/2 = 9.45 (billion yuans).

Input Specification:

Each input file contains one test case. For each case, the first line contains 2 positive integers N (<=1000), the number of different kinds of mooncakes, and D (<=500 thousand tons), the maximum total demand of the market. Then the second line gives the positive inventory amounts (in thousand tons), and the third line gives the positive prices (in billion yuans) of N kinds of mooncakes. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the maximum profit (in billion yuans) in one line, accurate up to 2 decimal places.

Sample Input:

3 200
180 150 100
7.5 7.2 4.5

Sample Output:

9.45

 

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1000+5;
int N, D;
struct node{
   double amount, price, average;
   bool operator < (const node &rhs) const{
     return average > rhs.average;
   }
}a[ MAXN ];


int main(){
   cin >> N >> D;
   for(int i = 0; i < N; i++) scanf("%lf", &a[i].amount);
   for(int i = 0; i < N; i++){
      scanf("%lf", &a[i].price);
      a[i].average = a[i].price / a[i].amount;
   }
   sort(a, a+N);
   double sum = 0.0;
   for(int i = 0; i < N && D > 0; i++){
      if( D > a[i].amount ) {
         sum += a[i].price;
         D -= a[i].amount;
      }
      else{
         sum += ( (D*a[i].average) );
         D = 0;
      }
   }
   printf("%.2f\n", sum);
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1071 Speech Patterns (25)(25 分)

People often have a preference among synonyms of the same word. For example, some may prefer "the police", while others may prefer "the cops". Analyzing such patterns can help to narrow down a speaker's identity, which is useful when validating, for example, whether it's still the same person behind an online avatar.

Now given a paragraph of text sampled from someone's speech, can you find the person's most commonly used word?

Input Specification:

Each input file contains one test case. For each case, there is one line of text no more than 1048576 characters in length, terminated by a carriage return '\n'. The input contains at least one alphanumerical character, i.e., one character from the set [0-9 A-Z a-z].

Output Specification:

For each test case, print in one line the most commonly occurring word in the input text, followed by a space and the number of times it has occurred in the input. If there are more than one such words, print the lexicographically smallest one. The word should be printed in all lower case. Here a "word" is defined as a continuous sequence of alphanumerical characters separated by non-alphanumerical characters or the line beginning/end.

Note that words are case insensitive.

Sample Input:

Can1: "Can a can can a can?  It can!"

Sample Output:

can 5

 

#include<bits/stdc++.h>
using namespace std;

string s, ans;
map <string, int> Mymap;
int main(){
   getline(cin ,s);
   for(auto &i: s){
      if( isupper(i) ) i = tolower(i);
      else if( !islower(i) && !isdigit(i) ) i = ' ';
   }
   stringstream ss(s);
   while(ss >> s)   Mymap[s]++;
   int maxn = -1;
   for(auto it : Mymap) if(it.second > maxn ){
      ans = it.first;
      maxn = it.second;
   }
   cout << ans << " " << maxn << endl;
   return 0;
}

 

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1072 Gas Station (30)(30 分)

A gas station has to be built at such a location that the minimum distance between the station and any of the residential housing is as far away as possible. However it must guarantee that all the houses are in its service range.

Now given the map of the city and several candidate locations for the gas station, you are supposed to give the best recommendation. If there are more than one solution, output the one with the smallest average distance to all the houses. If such a solution is still not unique, output the one with the smallest index number.

Input Specification:

Each input file contains one test case. For each case, the first line contains 4 positive integers: N (<= 10^3^), the total number of houses; M (<= 10), the total number of the candidate locations for the gas stations; K (<= 10^4^), the number of roads connecting the houses and the gas stations; and D~S~, the maximum service range of the gas station. It is hence assumed that all the houses are numbered from 1 to N, and all the candidate locations are numbered from G1 to GM.

Then K lines follow, each describes a road in the format\ P1 P2 Dist\ where P1 and P2 are the two ends of a road which can be either house numbers or gas station numbers, and Dist is the integer length of the road.

Output Specification:

For each test case, print in the first line the index number of the best location. In the next line, print the minimum and the average distances between the solution and all the houses. The numbers in a line must be separated by a space and be accurate up to 1 decimal place. If the solution does not exist, simply output “No Solution”.

Sample Input 1:

4 3 11 5
1 2 2
1 4 2
1 G1 4
1 G2 3
2 3 2
2 G2 1
3 4 2
3 G3 2
4 G1 3
G2 G1 1
G3 G2 2

Sample Output 1:

G1
2.0 3.3

Sample Input 2:

2 1 2 10
1 G1 9
2 G1 20

Sample Output 2:

No Solution
#include <bits/stdc++.h>
using namespace std;

const int MAXN = 1e3+50, INF = 99999999;
int N, M, K, D, n;
int d[MAXN][MAXN];
bool v[MAXN];
int dist[MAXN];
int MinDist = 0, DistSum = INF, Indix = INF;

int getid( char *p ){
   if( p[0] != 'G' ) return atoi(p);
   else return atoi(p+1)+N;
}

int main() {
    cin >> N >> M >> K >> D;
    n = N+M;
    while( K-- ){
       int P1, P2, Dist;
       char p1[10], p2[10];
       scanf("%s%s%d", p1, p2, &Dist);
       P1 = getid( p1 );
       P2 = getid( p2 );
       d[P2][P1] = d[P1][P2] = Dist;
	}
    
    for(int i = N+1; i <= n; i++){
       for(int j = 1; j <= n; j++) dist[j] = j == i ? 0 : INF;
       fill(v, v+MAXN, false);
       for(int t = 1; t <= n; t++){
          int x = -1, minn = INF;
          for(int y = 1; y <= n; y++) if( !v[y] && dist[y] < minn)
             minn = dist[x = y];
          if( x == -1 ) break;
          v[x] = true;
          for(int y = 1; y <= n; y++) if( !v[y] && d[x][y])
             dist[y] = min( dist[y], dist[x]+d[x][y] );
      }
    
       int TempMinDist = INF, TempDistSum = 0;
       bool ok = true;
       for(int i = 1; i <= N; i++){ 
          if( dist[i] > D) { ok = false;  break; }
          TempMinDist = min( TempMinDist, dist[i] );
          TempDistSum += dist[i];
       }
     
       if(ok && ( MinDist < TempMinDist || ( MinDist == TempMinDist && TempDistSum < DistSum ) ) ){ 
          DistSum = TempDistSum;
          MinDist = TempMinDist; 
          Indix = i;
       }
    }
    
    if( Indix == INF) printf("No Solution\n");
    else  printf("G%d\n%.1f %.1f\n", Indix-N, (double)MinDist, (double)DistSum*1.0/N);
    return 0;
}

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1073 Scientific Notation (20)(20 分)

Scientific notation is the way that scientists easily handle very large numbers or very small numbers. The notation matches the regular expression [+-][1-9]"."[0-9]+E[+-][0-9]+ which means that the integer portion has exactly one digit, there is at least one digit in the fractional portion, and the number and its exponent's signs are always provided even when they are positive.

Now given a real number A in scientific notation, you are supposed to print A in the conventional notation while keeping all the significant figures.

Input Specification:

Each input file contains one test case. For each case, there is one line containing the real number A in scientific notation. The number is no more than 9999 bytes in length and the exponent's absolute value is no more than 9999.

Output Specification:

For each test case, print in one line the input number A in the conventional notation, with all the significant figures kept, including trailing zeros,

Sample Input 1:

+1.23400E-03

Sample Output 1:

0.00123400

Sample Input 2:

-1.2E+10

Sample Output 2:

-12000000000

 

 

#include<bits/stdc++.h>
using namespace std;

int main(){
   string s, a, b;
   int B;
   cin >> s;
   if( s[0] == '-' )cout << '-';
   for(int i = 0;; i++) if( s[i] == 'E' ){
      a = s.substr(1, i-1) ;
      B = stoi( b = s.substr(i+1) );
      break;
   }
   int len = a.length();
   if(B < 0){
      B = -B;
      cout << "0.";
      for(int i = 1; i <= B-1; i++) cout << '0';
      for(auto i : a) if(i != '.') cout << i;
   }
   else{
      if( len-2 > B){
         B += 2;
         for(int i = 0; i < len; i++) {
             if( a[i] != '.') cout << a[i];
             if(--B == 0) cout << '.';
         }
      }
      else{
         for(int i = 0; i < len; i++) if( a[i] != '.') cout << a[i];
         for(int i = 0; i < (B-len+2); i++) cout << '0';
      }
   }
   return 0;
}

 

const int MAXN = 10000+10;
char s[MAXN], ss[MAXN];
int n;
cin >> s;
sscanf(s, "%[^E]E%d", ss, &n);

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1074 Reversing Linked List (25)(25 分)

Given a constant K and a singly linked list L, you are supposed to reverse the links of every K elements on L. For example, given L being 1→2→3→4→5→6, if K = 3, then you must output 3→2→1→6→5→4; if K = 4, you must output 4→3→2→1→5→6.

Input Specification:

Each input file contains one test case. For each case, the first line contains the address of the first node, a positive N (<= 10^5^) which is the total number of nodes, and a positive K (<=N) which is the length of the sublist to be reversed. The address of a node is a 5-digit nonnegative integer, and NULL is represented by -1.

Then N lines follow, each describes a node in the format:

Address Data Next

where Address is the position of the node, Data is an integer, and Next is the position of the next node.

Output Specification:

For each case, output the resulting ordered linked list. Each node occupies a line, and is printed in the same format as in the input.

Sample Input:

00100 6 4
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218

Sample Output:

00000 4 33218
33218 3 12309
12309 2 00100
00100 1 99999
99999 5 68237
68237 6 -1

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 100000+5;
struct node{
   int pos, v, next;
}temp, a[MAXN];

vector< node >v, ans ;

int N, L, K;

int main(){
   cin >> L >> N >> K;
   for(int i = 0; i < N; i++){
      scanf("%d %d %d", &temp.pos, &temp.v, &temp.next);
      a[temp.pos] = temp;
   }
   while(L != -1){
      v.push_back( a[L] );
      L = a[L].next;
   }
   int k = v.size() / K;
   for(int i = 0; i < k; i++)
      for(int j = K*(i+1)-1; j >= K*i; j--)
         ans.push_back( v[j] );
   for(int i = k*K; i < v.size(); i++) ans.push_back( v[i] );

   for(int i = 0; i < ans.size(); i++)
      if(i != ans.size() - 1 ) printf("%05d %d %05d\n", ans[i].pos, ans[i].v, ans[i+1].pos);
      else printf("%05d %d -1\n", ans[i].pos, ans[i].v);
   return 0;
}

 

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1075 PAT Judge (25)(25 分)

The ranklist of PAT is generated from the status list, which shows the scores of the submittions. This time you are supposed to generate the ranklist for PAT.

Input Specification:

Each input file contains one test case. For each case, the first line contains 3 positive integers, N (<=10^4^), the total number of users, K (<=5), the total number of problems, and M (<=10^5^), the total number of submittions. It is then assumed that the user id's are 5-digit numbers from 00001 to N, and the problem id's are from 1 to K. The next line contains K positive integers p[i] (i=1, ..., K), where p[i] corresponds to the full mark of the i-th problem. Then M lines follow, each gives the information of a submittion in the following format:

user_id problem_id partial_score_obtained

where partial_score_obtained is either -1 if the submittion cannot even pass the compiler, or is an integer in the range [0, p[problem_id]]. All the numbers in a line are separated by a space.

Output Specification:

For each test case, you are supposed to output the ranklist in the following format:

rank user_id total_score s[1] ... s[K]

where rank is calculated according to the total_score, and all the users with the same total_score obtain the same rank; and s[i] is the partial score obtained for the i-th problem. If a user has never submitted a solution for a problem, then "-" must be printed at the corresponding position. If a user has submitted several solutions to solve one problem, then the highest score will be counted.

The ranklist must be printed in non-decreasing order of the ranks. For those who have the same rank, users must be sorted in nonincreasing order according to the number of perfectly solved problems. And if there is still a tie, then they must be printed in increasing order of their id's. For those who has never submitted any solution that can pass the compiler, or has never submitted any solution, they must NOT be shown on the ranklist. It is guaranteed that at least one user can be shown on the ranklist.

Sample Input:

7 4 20
20 25 25 30
00002 2 12
00007 4 17
00005 1 19
00007 2 25
00005 1 20
00002 2 2
00005 1 15
00001 1 18
00004 3 25
00002 2 25
00005 3 22
00006 4 -1
00001 2 18
00002 1 20
00004 1 15
00002 4 18
00001 3 4
00001 4 2
00005 2 -1
00004 2 0

Sample Output:

1 00002 63 20 25 - 18
2 00005 42 20 0 22 -
2 00007 42 - 25 - 17
2 00001 42 18 18 4 2
5 00004 40 15 0 25 -

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 100000+5, MAXP = 5+2;;
int p[MAXP];

struct node{
   int score[MAXP], mark[MAXP];
   int Rank, id, sum, perfect, flag;
   bool operator < (const node &rhs) const{
      if(flag != rhs.flag) return flag > rhs.flag;
      else if(sum != rhs.sum) return sum > rhs.sum;
      else if(perfect != rhs.perfect) return perfect > rhs.perfect;
      else return id < rhs.id;
   }
}a[MAXN];

int main(){
   int N, K, M;
   cin >> N >> K >> M;
   for(int i = 0; i < K; i++) scanf("%d", &p[i]);
   while( M-- ){
      int id, promble, point;
      scanf("%d%d%d", &id, &promble, &point);
      a[id].id = id; promble--;
      if( a[id].score[promble] < point ){
         a[id].sum = a[id].sum - a[id].score[promble] + point;
         a[id].score[promble] = point;
         if(point == p[promble]) a[id].perfect++;
      }
      a[id].mark[ promble ] = 1;
      if( point >= 0) a[id].flag = 1;
   }
   sort(a+1, a+N+1);
   for(int i = 1; i <= N; i++){
      if( a[i].sum == a[i-1].sum ) a[i].Rank = a[i-1].Rank;
      else a[i].Rank = i;
   }

   for(int i = 1; i <= N; i++){
      if(a[i].flag <= 0) break;
      printf("%d %05d %d", a[i].Rank, a[i].id, a[i].sum);
      for(int k = 0; k < K; k++){
         if( a[i].mark[k] != 0 ) cout << " " << a[i].score[k];
         else cout << " -";
      }
      putchar('\n');
   }
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1076 Forwards on Weibo (30)(30 分)

Weibo is known as the Chinese version of Twitter. One user on Weibo may have many followers, and may follow many other users as well. Hence a social network is formed with followers relations. When a user makes a post on Weibo, all his/her followers can view and forward his/her post, which can then be forwarded again by their followers. Now given a social network, you are supposed to calculate the maximum potential amount of forwards for any specific user, assuming that only L levels of indirect followers are counted.

Input Specification:

Each input file contains one test case. For each case, the first line contains 2 positive integers: N (<=1000), the number of users; and L (<=6), the number of levels of indirect followers that are counted. Hence it is assumed that all the users are numbered from 1 to N. Then N lines follow, each in the format:

M[i] user_list[i]

where M[i] (<=100) is the total number of people that user[i] follows; and user_list[i] is a list of the M[i] users that are followed by user[i]. It is guaranteed that no one can follow oneself. All the numbers are separated by a space.

Then finally a positive K is given, followed by K UserID's for query.

Output Specification:

For each UserID, you are supposed to print in one line the maximum potential amount of forwards this user can triger, assuming that everyone who can view the initial post will forward it once, and that only L levels of indirect followers are counted.

Sample Input:

7 3
3 2 3 4
0
2 5 6
2 3 1
2 3 4
1 4
1 5
2 2 6

Sample Output:

4
5
#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1e3+10;
vector< vector< int > > v;
bool c[MAXN];
int N, L, Q, cnt, sum;

void bfs(int i){
   cnt = sum = 0;
   fill(c, c+N+1, false); 
   queue< int > Q;
   Q.push(i);
   c[i] = true;
   while( !Q.empty() && cnt++ <= L){
      int Size = Q.size();
      sum += Size;
      while( Size-- ){
      	 vector< int > &t = v[ Q.front() ];
      	 Q.pop();
      	 for(int j = 0; j < t.size(); j++) if( !c[ t[j] ] ){
      	    c[ t[j] ] = true;
	    Q.push( t[j] );
         }
      }
   }
   cout << sum-1 << endl;
}

int main(){
   cin >> N >> L;
   v.resize( N+1 );
   for(int i = 1; i <= N; i++){
      int n, x;
      scanf("%d", &n);
      while( n-- ){
        scanf("%d", &x);
        v[x].push_back(i);
      }
   }
   cin >> Q;
   while( Q-- ){
      int x;
      scanf("%d", &x);
      bfs(x);
   }
   return 0;
}

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1077 Kuchiguse (20)(20 分)

The Japanese language is notorious for its sentence ending particles. Personal preference of such particles can be considered as a reflection of the speaker's personality. Such a preference is called "Kuchiguse" and is often exaggerated artistically in Anime and Manga. For example, the artificial sentence ending particle "nyan~" is often used as a stereotype for characters with a cat-like personality:

Itai nyan~ (It hurts, nyan~)

Ninjin wa iyada nyan~ (I hate carrots, nyan~)

Now given a few lines spoken by the same character, can you find her Kuchiguse?

Input Specification:

Each input file contains one test case. For each case, the first line is an integer N (2<=N<=100). Following are N file lines of 0~256 (inclusive) characters in length, each representing a character's spoken line. The spoken lines are case sensitive.

Output Specification:

For each test case, print in one line the kuchiguse of the character, i.e., the longest common suffix of all N lines. If there is no such suffix, write "nai".

Sample Input 1:

3
Itai nyan~
Ninjin wa iyadanyan~
uhhh nyan~

Sample Output 1:

nyan~

Sample Input 2:

3
Itai!
Ninjinnwaiyada T_T
T_T

Sample Output 2:

nai

 

#include<bits/stdc++.h>
using namespace std;

vector< string >v;
int main(){
   int N;
   string a;
   cin >> N;
   getchar();
   for(int i = 0; i < N; i++){
      getline(cin, a);
      reverse(a.begin(), a.end());
      v.push_back( a );
   }
   int i = 0;
   for(; i < v[0].size(); i++){
      char c = v[0][i];
      bool ok = true;
      for(int j = 1; j < N; j++)
         if( i >= v[j].size() || v[j][i] != c ) ok = false;
      if( !ok ) break;
   }
   if( i )  for(int j = i-1; j >= 0; j--) cout << v[0][j];
   else cout << "nai\n";
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1078 Hashing (25)(25 分)

The task of this problem is simple: insert a sequence of distinct positive integers into a hash table, and output the positions of the input numbers. The hash function is defined to be "H(key) = key % TSize" where TSize is the maximum size of the hash table. Quadratic probing (with positive increments only) is used to solve the collisions.

Note that the table size is better to be prime. If the maximum size given by the user is not prime, you must re-define the table size to be the smallest prime number which is larger than the size given by the user.

Input Specification:

Each input file contains one test case. For each case, the first line contains two positive numbers: MSize (<=10^4^) and N (<=MSize) which are the user-defined table size and the number of input numbers, respectively. Then N distinct positive integers are given in the next line. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the corresponding positions (index starts from 0) of the input numbers in one line. All the numbers in a line are separated by a space, and there must be no extra space at the end of the line. In case it is impossible to insert the number, print "-" instead.

Sample Input:

4 4
10 6 4 15

Sample Output:

0 1 4 -
#include<bits/stdc++.h>

using namespace std;

bool isprime( int n ){
   if( n <= 1 ) return false;
   for(int i = 2; i <= sqrt(n)+0.5; i++){
      if( n % i == 0 ) return false;
   }
   return true;
}

int main(){
   int MSize, N;
   cin >> MSize >> N;
   for(int i = MSize;; i++) if( isprime(i) ){
      MSize = i; break;
   }
   vector< int > v(MSize, -1), p(N, -1);
   int x, k = MSize/2;
   for(int j = 0; j < N; j++){
      scanf("%d", &x);
      for(int i = 0; i <= k; i++) if( v[ (i*i+x)%MSize ] == -1){
          v[ p[j] = (i*i+x)%MSize ] = x;
          break;
      }
   }
   for(int i = 0; i < N; i++){
      if(i) putchar(' ');
      if( p[i] == -1) putchar('-');
      else printf("%d", p[i]);
   }
   return 0;
}

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1079 Total Sales of Supply Chain (25)(25 分)

A supply chain is a network of retailers(零售商), distributors(经销商), and suppliers(供应商)-- everyone involved in moving a product from supplier to customer.

Starting from one root supplier, everyone on the chain buys products from one's supplier in a price P and sell or distribute them in a price that is r% higher than P. Only the retailers will face the customers. It is assumed that each member in the supply chain has exactly one supplier except the root supplier, and there is no supply cycle.

Now given a supply chain, you are supposed to tell the total sales from all the retailers.

Input Specification:

Each input file contains one test case. For each case, the first line contains three positive numbers: N (<=10^5^), the total number of the members in the supply chain (and hence their ID's are numbered from 0 to N-1, and the root supplier's ID is 0); P, the unit price given by the root supplier; and r, the percentage rate of price increment for each distributor or retailer. Then N lines follow, each describes a distributor or retailer in the following format:

K~i~ ID[1] ID[2] ... ID[K~i~]

where in the i-th line, K~i~ is the total number of distributors or retailers who receive products from supplier i, and is then followed by the ID's of these distributors or retailers. K~j~ being 0 means that the j-th member is a retailer, then instead the total amount of the product will be given after K~j~. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the total sales we can expect from all the retailers, accurate up to 1 decimal place. It is guaranteed that the number will not exceed 10^10^.

Sample Input:

10 1.80 1.00
3 2 3 5
1 9
1 4
1 7
0 7
2 6 1
1 8
0 9
0 4
0 3

Sample Output:

42.

 

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1e5+10;
vector< int > v[MAXN];
int w[MAXN];
double Sum = 0.0,P ,R;

void dfs(int i, double money){
   if( v[i].empty() )   Sum += ( money*w[i] );
   else for(auto &j : v[i])   dfs(j, money*R);
   return;
}


int main(){
   int N, n, x;
   cin >> N >> P >> R;
   R = R/100 + 1;
   for(int i = 0; i < N; i++){
      scanf("%d", &n);
      if( !n )   scanf("%d", &w[i]);
      else while( n-- ){
         scanf("%d", &x);
         v[i].push_back(x);
      }
   }

   dfs(0, P);
   printf("%.1f\n", Sum);
   return 0;
}

 

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1080 Graduate Admission (30)(30 分)

It is said that in 2013, there were about 100 graduate schools ready to proceed over 40,000 applications in Zhejiang Province. It would help a lot if you could write a program to automate the admission procedure.

Each applicant will have to provide two grades: the national entrance exam grade G~E~, and the interview grade G~I~. The final grade of an applicant is (G~E~ + G~I~) / 2. The admission rules are:

  • The applicants are ranked according to their final grades, and will be admitted one by one from the top of the rank list.
  • If there is a tied final grade, the applicants will be ranked according to their national entrance exam grade G~E~. If still tied, their ranks must be the same.
  • Each applicant may have K choices and the admission will be done according to his/her choices: if according to the rank list, it is one's turn to be admitted; and if the quota of one's most preferred shcool is not exceeded, then one will be admitted to this school, or one's other choices will be considered one by one in order. If one gets rejected by all of preferred schools, then this unfortunate applicant will be rejected.
  • If there is a tied rank, and if the corresponding applicants are applying to the same school, then that school must admit all the applicants with the same rank, even if its quota will be exceeded.

Input Specification:

Each input file contains one test case. Each case starts with a line containing three positive integers: N (<=40,000), the total number of applicants; M (<=100), the total number of graduate schools; and K (<=5), the number of choices an applicant may have.

In the next line, separated by a space, there are M positive integers. The i-th integer is the quota of the i-th graduate school respectively.

Then N lines follow, each contains 2+K integers separated by a space. The first 2 integers are the applicant's G~E~ and G~I~, respectively. The next K integers represent the preferred schools. For the sake of simplicity, we assume that the schools are numbered from 0 to M-1, and the applicants are numbered from 0 to N-1.

Output Specification:

For each test case you should output the admission results for all the graduate schools. The results of each school must occupy a line, which contains the applicants' numbers that school admits. The numbers must be in increasing order and be separated by a space. There must be no extra space at the end of each line. If no applicant is admitted by a school, you must output an empty line correspondingly.

Sample Input:

11 6 3
2 1 2 2 2 3
100 100 0 1 2
60 60 2 3 5
100 90 0 3 4
90 100 1 2 0
90 90 5 1 3
80 90 1 0 2
80 80 0 1 2
80 80 0 1 2
80 70 1 3 2
70 80 1 2 3
100 100 0 2 4

Sample Output:

0 10
3
5 6 7
2 8

1 4

 

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 4e4+10, MAXC = 100+10;
int N, M, K;
int quota[MAXC];
vector< int > v[MAXC];

struct node{
   int ID;
   int GE, GI;
   int c[5], choose;
   double average;
   bool operator < (const node &rhs){
      return (average == rhs.average) ? (GE > rhs.GE) : (average > rhs.average);
   }
};

bool judge(node &a, node &b, int school){
   if(a.average > b.average)  return false;
   if(a.GE > b.GE) return false;
   if(a.choose != school ) return false;
   return true;
}

int main(){
   cin >> N >> M >> K;
   vector< node > stu(N);
   for(int i = 0; i < M; i++) scanf("%d", &quota[i]);
   for(int i = 0; i < N; i++){
      scanf("%d%d", &stu[i].GE, &stu[i].GI);
      for(int j = 0; j < K; j++)  scanf("%d", &stu[i].c[j]);
      stu[i].ID = i; stu[i].average = (stu[i].GI+stu[i].GE)/2.0;
   }
   sort(stu.begin(), stu.end() );

   for(int i = 0; i < N; i++){
      node &t = stu[i];
      for(int j = 0; j < K; j++){
         int school = t.c[j];
         if( !i || quota[ school ] > 0 || judge(stu[i-1], stu[i], school) ){
            v[ school ].push_back( t.ID );
            quota[ school ]--;
            t.choose = school;
            break;
         }
      }
   }

   for(int i = 0; i < M; i++){
       sort(v[i].begin(), v[i].end());
       for(int j = 0; j < v[i].size(); j++){
          if( j ) cout << " ";
          cout << v[i][j];
       }
       cout << '\n';
   }
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1081 Rational Sum (20)(20 分)

Given N rational numbers in the form "numerator/denominator", you are supposed to calculate their sum.

Input Specification:

Each input file contains one test case. Each case starts with a positive integer N (<=100), followed in the next line N rational numbers "a1/b1 a2/b2 ..." where all the numerators and denominators are in the range of "long int". If there is a negative number, then the sign must appear in front of the numerator.

Output Specification:

For each test case, output the sum in the simplest form "integer numerator/denominator" where "integer" is the integer part of the sum, "numerator" < "denominator", and the numerator and the denominator have no common factor. You must output only the fractional part if the integer part is 0.

Sample Input 1:

5
2/5 4/15 1/30 -2/60 8/3

Sample Output 1:

3 1/3

Sample Input 2:

2
4/3 2/3

Sample Output 2:

2

Sample Input 3:

3
1/3 -1/6 1/8

Sample Output 3:

7/24

 

 

#include<bits/stdc++.h>
using namespace std;

int gcd(int a, int b){
   return (b == 0) ? a : gcd(b, a%b);
}

int main(){
   int N, a, b, A, B;
   cin >> N;
   for(int i = 0; i < N; i++){
      if(!i ) scanf("%d/%d", &A, &B);
      else {
         scanf("%d/%d", &a, &b);
         A = a*B + b*A;
         B = b*B;
      }
      int K = gcd(A, B);
      A = A / K;
      B = B / K;
   }
   if(A*B < 0){ cout << '-'; A = abs(A); B = abs(B); }
   if(!A)  cout << "0\n";
   else{
      if(A > B)  {
         cout << A/B;
         if( A = A%B ) cout << " ";
      }
      if( A )  cout << A << '/' << B << endl;

   }
   return 0;
}

 

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1082 Read Number in Chinese (25)(25 分)

Given an integer with no more than 9 digits, you are supposed to read it in the traditional Chinese way. Output "Fu" first if it is negative. For example, -123456789 is read as "Fu yi Yi er Qian san Bai si Shi wu Wan liu Qian qi Bai ba Shi jiu". Note: zero ("ling") must be handled correctly according to the Chinese tradition. For example, 100800 is "yi Shi Wan ling ba Bai".

Input Specification:

Each input file contains one test case, which gives an integer with no more than 9 digits.

Output Specification:

For each test case, print in a line the Chinese way of reading the number. The characters are separated by a space and there must be no extra space at the end of the line.

Sample Input 1:

-123456789

Sample Output 1:

Fu yi Yi er Qian san Bai si Shi wu Wan liu Qian qi Bai ba Shi jiu

Sample Input 2:

100800

Sample Output 2:

yi Shi Wan ling ba Bai

 

 

等待修正

#include<bits/stdc++.h>
using namespace std;

const string s1[] = {"ling", "yi", "er", "san", "si", "wu", "liu", "qi", "ba" , "jiu" };
const string s2[] = {"Qian", "Bai", "Shi"};
const string s3[] = {"Wan", "Yi"};
int n;
vector< string > v;

int main(){
   cin >> n;
   if( n < 0) { v.push_back("Fu"); n = -n; }
   int t = 3, flag = 0;
   while( t-- ){
     bool ok = false;
      string a = to_string( n / (int)( pow(10,4*t) + 0.5) );
      while(a.length() < 4) a = '0' + a;
      n %= (int)( pow(10,4*t) + 0.5);
      for(int i = 0; i < 4; i++){
         if(a[i] == '0' && flag) { v.push_back( s1[0] ); flag = 0; }
         else if(a[i] != '0'){
            v.push_back( s1[ a[i]-'0' ] );
            if(i < 3) v.push_back( s2[i] );
            flag = 1;
            ok = true;
         }
      }
      if( v.size() > 0 && v[ v.size()-1 ] == s1[0] ) { v.pop_back(); flag = 1; }
      if( ok && t > 0) v.push_back( s3[t-1] );
   }
   for(int i = 0; i < v.size(); i++){
     if(i) cout << " ";
     cout << v[i];
   }
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1083 List Grades (25)(25 分)

Given a list of N student records with name, ID and grade. You are supposed to sort the records with respect to the grade in non-increasing order, and output those student records of which the grades are in a given interval.

Input Specification:

Each input file contains one test case. Each case is given in the following format:

N
name[1] ID[1] grade[1]
name[2] ID[2] grade[2]
... ...
name[N] ID[N] grade[N]
grade1 grade2

where name[i] and ID[i] are strings of no more than 10 characters with no space, grade[i] is an integer in [0, 100], grade1 and grade2 are the boundaries of the grade's interval. It is guaranteed that all the grades are distinct.

Output Specification:

For each test case you should output the student records of which the grades are in the given interval [grade1, grade2] and are in non-increasing order. Each student record occupies a line with the student's name and ID, separated by one space. If there is no student's grade in that interval, output "NONE" instead.

Sample Input 1:

4
Tom CS000001 59
Joe Math990112 89
Mike CS991301 100
Mary EE990830 95
60 100

Sample Output 1:

Mike CS991301
Mary EE990830
Joe Math990112

Sample Input 2:

2
Jean AA980920 60
Ann CS01 80
90 95

Sample Output 2:

NONE

 

#include<bits/stdc++.h>
using namespace std;

struct node{
   char name[15], id[15];
   int point;
   bool operator < (const node &rhs) const{
     return point > rhs.point;
   }
};


int main(){
   int N;
   cin >> N;
   vector< node > v(N);
   for(int i = 0; i < N; i++)   scanf("%s%s%d", v[i].name, v[i].id, &v[i].point);
   sort(v.begin(), v.end() );

   int a, b, ok = 0;
   cin >> a >> b;
   for(auto &i : v){
      if(i.point > b) continue;
      else if(i.point >= a) { printf("%s %s\n", i.name, i.id); ok = 1; }
      else break;
   }
   if( !ok ) cout << "NONE\n";
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1084 Broken Keyboard (20)(20 分)

On a broken keyboard, some of the keys are worn out. So when you type some sentences, the characters corresponding to those keys will not appear on screen.

Now given a string that you are supposed to type, and the string that you actually type out, please list those keys which are for sure worn out.

Input Specification:

Each input file contains one test case. For each case, the 1st line contains the original string, and the 2nd line contains the typed-out string. Each string contains no more than 80 characters which are either English letters [A-Z] (case insensitive), digital numbers [0-9], or "_" (representing the space). It is guaranteed that both strings are non-empty.

Output Specification:

For each test case, print in one line the keys that are worn out, in the order of being detected. The English letters must be capitalized. Each worn out key must be printed once only. It is guaranteed that there is at least one worn out key.

Sample Input:

7_This_is_a_test
_hs_s_a_es

Sample Output:

7TI

 

 

#include<bits/stdc++.h>
using namespace std;


set< char > Right, Wrong;

int main(){
   string In, Out;
   cin >> In >> Out;
   for(auto &i : Out){
      if( islower(i) )  i = toupper(i);
      Right.insert(i);
   }

   for(auto &i : In){
      if( islower(i) )  i = toupper(i);
      if( Wrong.count(i) || Right.count(i) ) continue;
      cout << i;
      Wrong.insert(i);
   }
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1085 Perfect Sequence (25)(25 分)

Given a sequence of positive integers and another positive integer p. The sequence is said to be a "perfect sequence" if M <= m * p where M and m are the maximum and minimum numbers in the sequence, respectively.

Now given a sequence and a parameter p, you are supposed to find from the sequence as many numbers as possible to form a perfect subsequence.

Input Specification:

Each input file contains one test case. For each case, the first line contains two positive integers N and p, where N (<= 10^5^) is the number of integers in the sequence, and p (<= 10^9^) is the parameter. In the second line there are N positive integers, each is no greater than 10^9^.

Output Specification:

For each test case, print in one line the maximum number of integers that can be chosen to form a perfect subsequence.

Sample Input:

10 8
2 3 20 4 5 1 6 7 8 9

Sample Output:

8

 

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1e5+10;
int A[MAXN];
int N, P;
long int ans = 1;

int main(){
   cin >> N >> P;
   for(int i = 0; i < N; i++)   scanf("%d", &A[i]);
   sort(A, A+N);
   for(int i = N-1; i >= 0; i--){
      double k = A[i]*1.0 / P;
      ans = max( i - ( lower_bound(A, A+N, k) -A ) + 1, ans);
   }
   cout << ans << endl;
   return 0;
}

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1086 Tree Traversals Again (25)(25 分)

An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the stack operations are: push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5); push(6); pop(); pop(). Then a unique binary tree (shown in Figure 1) can be generated from this sequence of operations. Your task is to give the postorder traversal sequence of this tree.

\ Figure 1

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (<=30) which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to N). Then 2N lines follow, each describes a stack operation in the format: "Push X" where X is the index of the node being pushed onto the stack; or "Pop" meaning to pop one node from the stack.

Output Specification:

For each test case, print the postorder traversal sequence of the corresponding tree in one line. A solution is guaranteed to exist. All the numbers must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:

6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop

Sample Output:

3 4 2 6 5 1

 

 

 

#include<bits/stdc++.h>
using namespace std;

vector< int >inorder, preorder, postorder;

void getpostorder(int inl, int inr, int pre){
   if( inl > inr ) return;
   int i = inl;
   while( inorder[i] != preorder[pre] ) i++;
   getpostorder( inl, i-1, pre+1);
   getpostorder( i+1, inr, pre+1+i-inl);
   postorder.push_back( inorder[i] );
}

int main(){
   int N;
   stack< int > S;
   cin >> N;
   for(int i = 0; i < 2*N; i++){
      string op;
      cin >> op;
      if(op[1] == 'u'){
         int x;
         cin >> x;
         S.push(x);
         preorder.push_back(x);
      }
      else{
         inorder.push_back( S.top() );
         S.pop();
      }
   }

   getpostorder( 0, N-1, 0);

   for(int i = 0; i < N; i++){
     if( i ) putchar(' ');
     cout << postorder[i];
   }
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1087 All Roads Lead to Rome (30)(30 分)

Indeed there are many different tourist rou

tes from our city to Rome. You are supposed to find your clients the route with the least cost while gaining the most happiness.

Input Specification:

Each input file contains one test case. For each case, the first line contains 2 positive integers N (2<=N<=200), the number of cities, and K, the total number of routes between pairs of cities; followed by the name of the starting city. The next N-1 lines each gives the name of a city and an integer that represents the happiness one can gain from that city, except the starting city. Then K lines follow, each describes a route between two cities in the format "City1 City2 Cost". Here the name of a city is a string of 3 capital English letters, and the destination is always ROM which represents Rome.

Output Specification:

For each test case, we are supposed to find the route with the least cost. If such a route is not unique, the one with the maximum happiness will be recommended. If such a route is still not unique, then we output the one with the maximum average happiness -- it is guaranteed by the judge that such a solution exists and is unique.

Hence in the first line of output, you must print 4 numbers: the number of different routes with the least cost, the cost, the happiness, and the average happiness (take the integer part only) of the recommended route. Then in the next line, you are supposed to print the route in the format "City1->City2->...->ROM".

Sample Input:

6 7 HZH
ROM 100
PKN 40
GDN 55
PRS 95
BLN 80
ROM GDN 1
BLN ROM 1
HZH PKN 1
PRS ROM 2
BLN HZH 2
PKN GDN 1
HZH PRS 1

Sample Output:

3 3 195 97
HZH->PRS->ROM

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 200+5, inf = 9999999;
int N, M, S, cnt = 0;
char city[4], city2[4];
map< int, int > IDCache, NameCache;
int w[MAXN];
int d[MAXN][MAXN];
int dist[MAXN], road[MAXN], happy[MAXN], citysum[MAXN], path[MAXN];
int v[MAXN];

int getid(char *s)  {
   int id  = (s[0]-'A')*26*26 +(s[1]-'A')*26 +(s[2]-'A');
   if( !NameCache.count( id ) ){
      NameCache[ id ] = cnt;
      IDCache[ cnt++ ] = id;
   }
   return NameCache[ id ];
}

void getname(int i){
     int id = IDCache[i];
     cout << char(id/26/26+'A') << char( (id/26)%26+'A' ) << char( id%26+'A' );
}

void init(){
   cin >> N >> M >> city;
   S = getid( city );
   for(int i = 0; i < N-1; i++){
      int happiness;
      scanf("%s%d", city, &happiness);
      int id = getid( city );
      w[ id ] = happiness;
   }
}

int main(){
   init();
   for(int i = 0; i < M; i++){
      int distance;
      scanf("%s%s%d",city, city2, &distance);
      int a = getid(city), b = getid(city2);
      d[a][b] = d[b][a] = distance;
   }

   fill(dist, dist+MAXN, inf);
   dist[ S ] = 0;
   road[ S ] = 1;
   path[ S ] = -1;
   for(int i = 0; i < N; i++){
      int minn = inf, x = -1;
      for(int y = 0; y < N; y++) if(!v[y] && dist[y] < minn){
         minn = dist[ x = y];
      }
      if( x < 0) break;
      v[x] = 1;
      for(int y = 0; y < N; y++) if(!v[y] && d[x][y]){
          if( dist[y] > dist[x] + d[x][y]){
             dist[y] = dist[x] + d[x][y];
             road[y] = road[x];
             happy[y] = happy[x] + w[y];
             citysum[y] = citysum[x]+1;
             path[y] = x;
          }
          else if(dist[y] == dist[x] + d[x][y]){
             road[y] += road[x];
             if(happy[y] < happy[x]+w[y] || (happy[y] == happy[x]+w[y] && citysum[y] > citysum[x]+1) ){
                 happy[y] = happy[x]+w[y];
                 citysum[y] = citysum[x]+1;
                 path[y] = x;
             }
          }
      }
   }
   memcpy(city, "ROM", sizeof(city));
   int c = getid(city);
   vector< int > ans;
   for(int i = c; i != -1; i = path[i]) ans.push_back(i);
   cout << road[c] << " " << dist[c] << " " << happy[c] << " " << happy[c]/citysum[c] << endl;
   for(int i = (int)ans.size()-1; i >= 0; i--){
      getname( ans[i] );
      if(i) cout << "->";
   }
   return 0;
}

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1088 Rational Arithmetic (20)(20 分)

For two rational numbers, your task is to implement the basic arithmetics, that is, to calculate their sum, difference, product and quotient.

Input Specification:

Each input file contains one test case, which gives in one line the two rational numbers in the format "a1/b1 a2/b2". The numerators and the denominators are all in the range of long int. If there is a negative sign, it must appear only in front of the numerator. The denominators are guaranteed to be non-zero numbers.

Output Specification:

For each test case, print in 4 lines the sum, difference, product and quotient of the two rational numbers, respectively. The format of each line is "number1 operator number2 = result". Notice that all the rational numbers must be in their simplest form "k a/b", where k is the integer part, and a/b is the simplest fraction part. If the number is negative, it must be included in a pair of parentheses. If the denominator in the division is zero, output "Inf" as the result. It is guaranteed that all the output integers are in the range of long int.

Sample Input 1:

2/3 -4/2

Sample Output 1:

2/3 + (-2) = (-1 1/3)
2/3 - (-2) = 2 2/3
2/3 * (-2) = (-1 1/3)
2/3 / (-2) = (-1/3)

Sample Input 2:

5/3 0/6

Sample Output 2:

1 2/3 + 0 = 1 2/3
1 2/3 - 0 = 1 2/3
1 2/3 * 0 = 0
1 2/3 / 0 = Inf

 

 

#include<bits/stdc++.h>
using namespace std;

typedef long long ll;
ll gcd(ll a, ll b){
   return (b == 0) ? a : gcd(b, a%b);
}


void form(ll A, ll B){
   ll K = gcd( abs(A), abs(B) );
   A = A / K;
   B = B / K;
   bool ok = false;
   if( (A < 0 && B > 0) || (A > 0 && B < 0) ){ cout << "(-"; A = abs(A); B = abs(B); ok = true;}
   if( A/B  ){
       cout<< A/B;
       if( A % B ) cout<< " " << A%B << "/" << B;
    }
    else{
       if( A % B ) cout << A << "/" << B;
       else cout<<"0";
    }
    if( ok ) cout << ")";
}

ll a, b, c, d;

int main(){ 
   scanf("%lld/%lld %lld/%lld", &a, &b, &c, &d);
   form(a, b); cout << " + "; form(c, d); cout << " = "; form(a*d+b*c, b*d); cout << '\n';
   form(a, b); cout << " - "; form(c, d); cout << " = "; form(a*d-b*c, b*d); cout << '\n';
   form(a, b); cout << " * "; form(c, d); cout << " = "; form(a*c, b*d); cout << '\n';
   form(a, b); cout << " / "; form(c, d); cout << " = ";
   if(c == 0) cout << "Inf\n";
   else { form(a*d, b*c); cout << '\n'; }
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1089 Insert or Merge(25 分)

According to Wikipedia:

Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. Each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. It repeats until no input elements remain.

Merge sort works as follows: Divide the unsorted list into N sublists, each containing 1 element (a list of 1 element is considered sorted). Then repeatedly merge two adjacent sublists to produce new sorted sublists until there is only 1 sublist remaining.

Now given the initial sequence of integers, together with a sequence which is a result of several iterations of some sorting method, can you tell which sorting method we are using?

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤100). Then in the next line, N integers are given as the initial sequence. The last line contains the partially sorted sequence of the N numbers. It is assumed that the target sequence is always ascending. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in the first line either "Insertion Sort" or "Merge Sort" to indicate the method used to obtain the partial result. Then run this method for one more iteration and output in the second line the resuling sequence. It is guaranteed that the answer is unique for each test case. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line.

Sample Input 1:

10
3 1 2 8 7 5 9 4 6 0
1 2 3 7 8 5 9 4 6 0

Sample Output 1:

Insertion Sort
1 2 3 5 7 8 9 4 6 0

Sample Input 2:

10
3 1 2 8 7 5 9 4 0 6
1 3 2 8 5 7 4 9 0 6

Sample Output 2:

Merge Sort
1 2 3 8 4 5 7 9 0 6
#include<bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    int *a = new int [n], *b = new int [n];
    for (int i = 0; i < n; i++)  scanf("%d", &a[i]);
    for (int i = 0; i < n; i++)  scanf("%d", &b[i]);
    int i, j;
    for (i = 0; i < n - 1 && b[i] <= b[i + 1]; i++);
    for (j = i + 1; j < n && a[j] == b[j]; j++);
    if ( j == n ) {
        printf("Insertion Sort\n");
        sort(a, a+i+2);
    } else {
        printf("Merge Sort\n");
        int k = 1;
		bool ok = false;
        while( !ok ) {
            ok = true;
            for (i = 0; i < n; i++) if( a[i] != b[i] )
               ok = false;
            k *= 2;
            for (i = 0; i < n/k; i++)  sort( a+i*k, a+(i+1)*k );
            sort( a+n/k*k, a+n );
        }
    }
    for (int i = 0; i < n; i++)
        printf("%d%c", a[i], (i == n-1 ? '\n' : ' ') );
    delete [] a;   delete [] b;
    return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1090 Highest Price in Supply Chain (25)(25 分)

A supply chain is a network of retailers(零售商), distributors(经销商), and suppliers(供应商)-- everyone involved in moving a product from supplier to customer.

Starting from one root supplier, everyone on the chain buys products from one's supplier in a price P and sell or distribute them in a price that is r% higher than P. It is assumed that each member in the supply chain has exactly one supplier except the root supplier, and there is no supply cycle.

Now given a supply chain, you are supposed to tell the highest price we can expect from some retailers.

Input Specification:

Each input file contains one test case. For each case, The first line contains three positive numbers: N (<=10^5^), the total number of the members in the supply chain (and hence they are numbered from 0 to N-1); P, the price given by the root supplier; and r, the percentage rate of price increment for each distributor or retailer. Then the next line contains N numbers, each number S~i~ is the index of the supplier for the i-th member. S~root~ for the root supplier is defined to be -1. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the highest price we can expect from some retailers, accurate up to 2 decimal places, and the number of retailers that sell at the highest price. There must be one space between the two numbers. It is guaranteed that the price will not exceed 10^10^.

Sample Input:

9 1.80 1.00
1 5 4 4 -1 4 5 3 6

Sample Output:

1.85 2

 

#include<bits/stdc++.h>
using namespace std;

int N, head, cnt;
double r, p;
vector< vector< int > >v;
double maxsum = -1; 

void dfs(int i, double p){
   if( v[i].empty() ){
      if(p > maxsum) { maxsum = p; cnt = 1; }
      else if( abs(p-maxsum) < 1e-5 ) cnt++;
   }
   else for(auto &j : v[i])  dfs(j, p*r);
}

int main(){
   cin >> N >> p >> r;
   v.resize(N);
   r = r/100+1;
   for(int i = 0; i < N; i++){
      int x;
      scanf("%d", &x);
      if( x == -1) head = i;
      else v[x].push_back(i);
   }
   
   dfs(head, p);
   
   printf("%.2f %d\n", maxsum, cnt);
   return 0;
}

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1091 Acute Stroke (30)(30 分)

One important factor to identify acute stroke (急性脑卒中) is the volume of the stroke core. Given the results of image analysis in which the core regions are identified in each MRI slice, your job is to calculate the volume of the stroke core.

Input Specification:

Each input file contains one test case. For each case, the first line contains 4 positive integers: M, N, L and T, where M and N are the sizes of each slice (i.e. pixels of a slice are in an M by N matrix, and the maximum resolution is 1286 by 128); L (<=60) is the number of slices of a brain; and T is the integer threshold (i.e. if the volume of a connected core is less than T, then that core must not be counted).

Then L slices are given. Each slice is represented by an M by N matrix of 0's and 1's, where 1 represents a pixel of stroke, and 0 means normal. Since the thickness of a slice is a constant, we only have to count the number of 1's to obtain the volume. However, there might be several separated core regions in a brain, and only those with their volumes no less than T are counted. Two pixels are "connected" and hence belong to the same region if they share a common side, as shown by Figure 1 where all the 6 red pixels are connected to the blue one.

\ Figure 1

Output Specification:

For each case, output in a line the total volume of the stroke core.

Sample Input:

3 4 5 2
1 1 1 1
1 1 1 1
1 1 1 1
0 0 1 1
0 0 1 1
0 0 1 1
1 0 1 1
0 1 0 0
0 0 0 0
1 0 1 1
0 0 0 0
0 0 0 0
0 0 0 1
0 0 0 1
1 0 0 0

Sample Output:

26

 

#include<bits/stdc++.h>
using namespace std;

#define _for(i,a,b) for(int i = a; i < b; i++)
bool d[62][1288][130];
const int dx[] = {0,0,1,0,0,-1};
const int dy[] = {0,1,0,0,-1,0};
const int dz[] = {1,0,0,-1,0,0};
int N, M, L, T;
int cnt, ans = 0;

bool inside(int x, int y, int z){
   return (x >= 0 && y >= 0 && z >= 0 && x < L && y < M && z < N);
}

struct node{
   int x, y, z;
};

void bfs(int i, int j, int k){
   queue< node > Q;
   Q.push( {i, j, k} );
   while( !Q.empty() ){
      node temp = Q.front();
	  Q.pop(); 
      for(int t = 0; t < 6; t++){
         int x = temp.x + dx[t], y = temp.y + dy[t], z = temp.z + dz[t];
         if( inside(x, y, z) && d[x][y][z]){
            cnt++;
            d[x][y][z] = false;
            Q.push( {x,y,z} );
         }
      }
  }
}

int main(){
   cin >> M >> N >> L >> T;
   _for(i, 0, L)
      _for(j, 0, M)
         _for(k, 0, N){
            int x;
            scanf("%d", &x);
            if(x) d[i][j][k] = true;
         }
   _for(i, 0, L)
      _for(j, 0, M)
         _for(k, 0, N) if( d[i][j][k] ){
             cnt = 1;
             d[i][j][k] = false;
             bfs(i, j, k);
             if(cnt >= T) ans += cnt;
         }
  cout << ans << endl;
  return 0;
}

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1092 To Buy or Not to Buy (20)(20 分)

Eva would like to make a string of beads with her favorite colors so she went to a small shop to buy some beads. There were many colorful strings of beads. However the owner of the shop would only sell the strings in whole pieces. Hence Eva must check whether a string in the shop contains all the beads she needs. She now comes to you for help: if the answer is "Yes", please tell her the number of extra beads she has to buy; or if the answer is "No", please tell her the number of beads missing from the string.

For the sake of simplicity, let's use the characters in the ranges [0-9], [a-z], and [A-Z] to represent the colors. For example, the 3rd string in Figure 1 is the one that Eva would like to make. Then the 1st string is okay since it contains all the necessary beads with 8 extra ones; yet the 2nd one is not since there is no black bead and one less red bead.

\ Figure 1

Input Specification:

Each input file contains one test case. Each case gives in two lines the strings of no more than 1000 beads which belong to the shop owner and Eva, respectively.

Output Specification:

For each test case, print your answer in one line. If the answer is "Yes", then also output the number of extra beads Eva has to buy; or if the answer is "No", then also output the number of beads missing from the string. There must be exactly 1 space between the answer and the number.

Sample Input 1:

ppRYYGrrYBR2258
YrR8RrY

Sample Output 1:

Yes 8

Sample Input 2:

ppRYYGrrYB225
YrR8RrY

Sample Output 1:

No 2

 

#include<bits/stdc++.h>
using namespace std;


int main(){
   string a, b;
   cin >> a >> b;
   int len1 = a.length(), len2 = b.length();
   int m[256], cnt = 0;
   memset(m, 0, sizeof(m));
   for(auto i : a) m[i]++;
   for(auto i : b) {
      if( m[i] ) m[i]--;
      else cnt++;
   }
   if( !cnt ) cout << "Yes " << len1 - len2 << endl;
   else cout << "No " << cnt << endl;
   return 0;
}

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1093 Count PAT's (25)(25 分)

The string APPAPT contains two PAT's as substrings. The first one is formed by the 2nd, the 4th, and the 6th characters, and the second one is formed by the 3rd, the 4th, and the 6th characters.

Now given any string, you are supposed to tell the number of PAT's contained in the string.

Input Specification:

Each input file contains one test case. For each case, there is only one line giving a string of no more than 10^5^ characters containing only P, A, or T.

Output Specification:

For each test case, print in one line the number of PAT's contained in the string. Since the result may be a huge number, you only have to output the result moded by 1000000007.

Sample Input:

APPAPT

Sample Output:

2

 

#include<bits/stdc++.h>
using namespace std;

const long int MOD = 1000000007;

int main(){
   string s;
   cin >> s;
   const int N = s.length();
   vector< int > v(N);
   if(s[N-1] == 'T') v[N-1] = 1;
   for(int i = N-2; i > 0; i--)
      v[i] = ( s[i] == 'T') ? ( v[i+1] + 1 ): v[i+1];
   long int sum = 0, ans = 0;

   for(int i = 0; i < N; i++){
      if( s[i] == 'P' ) sum++;
      else if( s[i] == 'A' ) ans = (ans + (sum*v[i]) % MOD ) % MOD;
   }
   cout << ans << endl;
   return 0;
}

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1094 The Largest Generation (25)(25 分)

A family hierarchy is usually presented by a pedigree tree where all the nodes on the same level belong to the same generation. Your task is to find the generation with the largest population.

Input Specification:

Each input file contains one test case. Each case starts with two positive integers N (&lt100) which is the total number of family members in the tree (and hence assume that all the members are numbered from 01 to N), and M (&ltN) which is the number of family members who have children. Then M lines follow, each contains the information of a family member in the following format:

ID K ID[1] ID[2] ... ID[K]

where ID is a two-digit number representing a family member, K (&gt0) is the number of his/her children, followed by a sequence of two-digit ID's of his/her children. For the sake of simplicity, let us fix the root ID to be 01. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the largest population number and the level of the corresponding generation. It is assumed that such a generation is unique, and the root level is defined to be 1.

Sample Input:

23 13
21 1 23
01 4 03 02 04 05
03 3 06 07 08
06 2 12 13
13 1 21
08 2 15 16
02 2 09 10
11 2 19 20
17 1 22
05 1 11
07 1 14
09 1 17
10 1 18

Sample Output:

9 4

 

 

 

#include<bits/stdc++.h>
using namespace std;


int N, M;
vector< vector< int > > v;
queue< int > q;


int main(){
   cin >> N >> M;
   v.resize( N+1 );
   while( M-- ){
      int ID, K, x;
      cin >> ID >> K;
      while( K-- ){
         scanf("%d", &x);
         v[ID].push_back(x);
      }
   }
   q.push(1);
   int deep = 1, maxsize = 1, generation = 1;
   while( !q.empty() ){
     int Size = q.size();
     if(maxsize < Size){
        maxsize = Size;
        generation = deep;
     }

     while( Size-- ){
        vector <int> &t = v[ q.front() ];
        q.pop();
        for(auto i : t) q.push( i );
     }
     deep++;
   }

   cout << maxsize << " " << generation << endl;
   return 0;
}

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1095 Cars on Campus (30)(30 分)

Zhejiang University has 6 campuses and a lot of gates. From each gate we can collect the in/out times and the plate numbers of the cars crossing the gate. Now with all the information available, you are supposed to tell, at any specific time point, the number of cars parking on campus, and at the end of the day find the cars that have parked for the longest time period.

Input Specification:

Each input file contains one test case. Each case starts with two positive integers N (<= 10000), the number of records, and K (<= 80000) the number of queries. Then N lines follow, each gives a record in the format

plate_number hh:mm:ss status

where plate_number is a string of 7 English capital letters or 1-digit numbers; hh:mm:ss represents the time point in a day by hour:minute:second, with the earliest time being 00:00:00 and the latest 23:59:59; and status is either in or out.

Note that all times will be within a single day. Each "in" record is paired with the chronologically next record for the same car provided it is an "out" record. Any "in" records that are not paired with an "out" record are ignored, as are "out" records not paired with an "in" record. It is guaranteed that at least one car is well paired in the input, and no car is both "in" and "out" at the same moment. Times are recorded using a 24-hour clock.

Then K lines of queries follow, each gives a time point in the format hh:mm:ss. Note: the queries are given in ascending order of the times.

Output Specification:

For each query, output in a line the total number of cars parking on campus. The last line of output is supposed to give the plate number of the car that has parked for the longest time period, and the corresponding time length. If such a car is not unique, then output all of their plate numbers in a line in alphabetical order, separated by a space.

Sample Input:

16 7
JH007BD 18:00:01 in
ZD00001 11:30:08 out
DB8888A 13:00:00 out
ZA3Q625 23:59:50 out
ZA133CH 10:23:00 in
ZD00001 04:09:59 in
JH007BD 05:09:59 in
ZA3Q625 11:42:01 out
JH007BD 05:10:33 in
ZA3Q625 06:30:50 in
JH007BD 12:23:42 out
ZA3Q625 23:55:00 in
JH007BD 12:24:23 out
ZA133CH 17:11:22 out
JH007BD 18:07:01 out
DB8888A 06:30:50 in
05:10:00
06:30:50
11:00:00
12:23:42
14:00:00
18:00:00
23:59:00

Sample Output:

1
4
5
2
1
0
1
JH007BD ZD00001 07:20:09

 

 


#include<bits/stdc++.h>
using namespace std;

const int MAXN = 10000+10, MAXT = 25*60*60+10;
int N, Q, Longest = -1;
set< string > Ansid;


struct node{
   string ID;
   int Time;
   int status;
   bool operator < (const node &rhs) const {
      return (ID != rhs.ID) ? ( ID < rhs.ID ) : ( Time < rhs.Time );
   }
} Record[MAXN];

bool cmp(node a, node b){
	return a.Time < b.Time;
}



int main(){
   cin >> N >> Q;
   for(int i = 0; i < N; i++){
      int hh, mm, ss;
      char id[10], status[5];
      scanf("%s%d:%d:%d%s", id, &hh, &mm, &ss, status);
      Record[i].ID = id;
      Record[i].Time = hh*60*60 + mm*60 + ss;
      Record[i].status = (status[0] == 'i') ? 1 : -1;
   }
   sort( Record, Record+N );
   vector< node > Car;
   string id;
   int Time;

   for(int i = 1; i < N; i++){
       if( Record[i].status == -1 && Record[i-1].status == 1 && Record[i].ID == Record[i-1].ID){
             if(Record[i].ID != id)   Time = 0;
             id = Record[i].ID;
             Time += Record[i].Time - Record[i-1].Time;
             if( Time > Longest ) {
                Ansid.clear();
                Longest = Time;
             }
             if( Time == Longest ) Ansid.insert( id );
             Car.push_back(  Record[i-1] );
             Car.push_back(  Record[i] );
       }
   }
   sort(Car.begin(), Car.end(), cmp);
   int Count = 0, st = 0;
   while( Q-- ){
      int hh, mm, ss, tt, i = st;
      scanf("%d:%d:%d", &hh, &mm, &ss);
      tt = hh*60*60 + mm*60 + ss;
      for(; i < Car.size(); i++){
      	 if( Car[i].Time > tt ) break;
      	 Count += Car[i].status;
      }
      st = i;
      cout << Count << endl;
   }

   for(set< string >::iterator it = Ansid.begin(); it != Ansid.end(); it++) cout << *it <<" ";
   printf("%02d:%02d:%02d\n", Longest/60/60, Longest/60%60, Longest%60);
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1096 Consecutive Factors (20)(20 分)

Among all the factors of a positive integer N, there may exist several consecutive numbers. For example, 630 can be factored as 3*5*6*7, where 5, 6, and 7 are the three consecutive numbers. Now given any positive N, you are supposed to find the maximum number of consecutive factors, and list the smallest sequence of the consecutive factors.

Input Specification:

Each input file contains one test case, which gives the integer N (1<N<2^31^).

Output Specification:

For each test case, print in the first line the maximum number of consecutive factors. Then in the second line, print the smallest sequence of the consecutive factors in the format "factor[1]*factor[2]*...*factor[k]", where the factors are listed in increasing order, and 1 is NOT included.

Sample Input:

630

Sample Output:

3
5*6*7

 

#include<bits/stdc++.h>
using namespace std;

typedef long long LL;

LL mul(int len){
   LL res = 1;
   for(int i = 2; i < 2+len; i++) res *= i;
   return res;
}

bool isprime(LL N){
   if(N <= 1) return false;
   for(int i = 2; i <= sqrt(N)+0.5; i++)
      if(N % i == 0) return false;
   return true;
}

int main(){
   LL N;
   int p, q;
   cin >> N;
   if( isprime(N) ) cout << "1\n" << N <<endl;
   else for(int len = 11; len >= 1; len--){
      p = 2, q = 1+len;
      LL sum = mul( len );
      while( sum <= N ){
         if( N % sum == 0 ){
            cout << q+1-p << endl << p;
            while(p < q) cout << '*' << ++p;
            return 0;
         }
         sum = sum / p++ * ++q;
      }
   }
   return 0;
}

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1097 Deduplication on a Linked List (25)(25 分)

Given a singly linked list L with integer keys, you are supposed to remove the nodes with duplicated absolute values of the keys. That is, for each value K, only the first node of which the value or absolute value of its key equals K will be kept. At the mean time, all the removed nodes must be kept in a separate list. For example, given L being 21→-15→-15→-7→15, you must output 21→-15→-7, and the removed list -15→15.

Input Specification:

Each input file contains one test case. For each case, the first line contains the address of the first node, and a positive N (<= 10^5^) which is the total number of nodes. The address of a node is a 5-digit nonnegative integer, and NULL is represented by -1.

Then N lines follow, each describes a node in the format:

Address Key Next

where Address is the position of the node, Key is an integer of which absolute value is no more than 10^4^, and Next is the position of the next node.

Output Specification:

For each case, output the resulting linked list first, then the removed list. Each node occupies a line, and is printed in the same format as in the input.

Sample Input:

00100 5
99999 -7 87654
23854 -15 00000
87654 15 -1
00000 -15 99999
00100 21 23854

Sample Output:

00100 21 23854
23854 -15 99999
99999 -7 -1
00000 -15 87654
87654 15 -1
#include<bits/stdc++.h>
using namespace std;

const int MAXN = 100000+10;
int T, N;


struct node{
   int add, key, next;
}a[MAXN];


int main(){
   cin >> T >> N;
   for( int i = 0; i< N; i++){
      node t;
      scanf("%d%d%d", &t.add, &t.key, &t.next);
      a[ t.add ] = t;
   }

   int p = T;
   vector< node > v;
   while( p != -1){
      v.push_back( a[p] );
      p = a[p].next;
   }

   unordered_set< int > Myset;
   vector< node > v1, v2;
   for(auto &i : v){
      if( Myset.count( abs(i.key) ) )   v2.push_back( i );
      else {
         v1.push_back( i );
         Myset.insert( abs(i.key) );
      }
   }
   for(int i = 0; i < v1.size(); i++){
      if(i != v1.size()-1 ) printf("%05d %d %05d\n", v1[i].add, v1[i].key, v1[i+1].add);
      else printf("%05d %d -1\n", v1[i].add, v1[i].key);
   }

   for(int i = 0; i < v2.size(); i++){
      if(i != v2.size()-1 ) printf("%05d %d %05d\n", v2[i].add, v2[i].key, v2[i+1].add);
      else printf("%05d %d -1\n", v2[i].add, v2[i].key);
   }

   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1098 Insertion or Heap Sort (25)(25 分)

According to Wikipedia:

Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. It repeats until no input elements remain.

Heap sort divides its input into a sorted and an unsorted region, and it iteratively shrinks the unsorted region by extracting the largest element and moving that to the sorted region. it involves the use of a heap data structure rather than a linear-time search to find the maximum.

Now given the initial sequence of integers, together with a sequence which is a result of several iterations of some sorting method, can you tell which sorting method we are using?

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (<=100). Then in the next line, N integers are given as the initial sequence. The last line contains the partially sorted sequence of the N numbers. It is assumed that the target sequence is always ascending. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in the first line either "Insertion Sort" or "Heap Sort" to indicate the method used to obtain the partial result. Then run this method for one more iteration and output in the second line the resuling sequence. It is guaranteed that the answer is unique for each test case. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line.

Sample Input 1:

10
3 1 2 8 7 5 9 4 6 0
1 2 3 7 8 5 9 4 6 0

Sample Output 1:

Insertion Sort
1 2 3 5 7 8 9 4 6 0

Sample Input 2:

10
3 1 2 8 7 5 9 4 6 0
6 4 5 1 0 3 2 7 8 9

Sample Output 2:

Heap Sort
5 4 3 1 0 2 6 7 8 9
#include<bits/stdc++.h>
using namespace std;

vector<int> a, b;
int n;

void downAdjust(int low, int high) {
    int i = 1, j = i * 2;
    while(j <= high) {
        if(j + 1 <= high && b[j] < b[j + 1]) j++;
        if(b[i] < b[j]) {
            swap(b[i], b[j]);
            i = j;   j = i * 2;
        } 
       else break;
    }
}


void print(){
   for(int i = 1; i <= n; i++)
      printf("%d%c", b[i], (i == n ? '\n' : ' '));
}

int main() {
    int p = 2;
    scanf("%d", &n);
    a.resize(n + 1), b.resize(n + 1);
    for(int i = 1; i <= n; i++)  scanf("%d", &a[i]);
    for(int i = 1; i <= n; i++)  scanf("%d", &b[i]);
    while(p <= n && b[p - 1] <= b[p]) p++;
    int index = p;
    while(p <= n && a[p] == b[p]) p++;
    if(p == n + 1) {
        printf("Insertion Sort\n");
        sort(b.begin() + 1, b.begin() + index + 1);
        print();
    }
    else {
        printf("Heap Sort\n");
        p = n;
        while(p >= 2 && b[p] >= b[p - 1]) p--;
        swap(b[1], b[p]);
        downAdjust(1, p - 1);
        print();
    }
    return 0;
}

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1099 Build A Binary Search Tree (30)(30 分)

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:

The left subtree of a node contains only nodes with keys less than the node's key.

The right subtree of a node contains only nodes with keys greater than or equal to the node's key.

Both the left and right subtrees must also be binary search trees.

Given the structure of a binary tree and a sequence of distinct integer keys, there is only one way to fill these keys into the tree so that the resulting tree satisfies the definition of a BST. You are supposed to output the level order traversal sequence of that tree. The sample is illustrated by Figure 1 and 2.

 

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (<=100) which is the total number of nodes in the tree. The next N lines each contains the left and the right children of a node in the format "left_index right_index", provided that the nodes are numbered from 0 to N-1, and 0 is always the root. If one child is missing, then -1 will represent the NULL child pointer. Finally N distinct integer keys are given in the last line.

Output Specification:

For each test case, print in one line the level order traversal sequence of that tree. All the numbers must be separated by a space, with no extra space at the end of the line.

Sample Input:

9
1 6
2 3
-1 -1
-1 4
5 -1
-1 -1
7 -1
-1 8
-1 -1
73 45 11 58 82 25 67 38 42

Sample Output:

58 25 82 11 38 67 45 73 42

 

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 100000+10;
int N, Left, Right;
int A[MAXN][2], cnt;
vector< int > pre, level, v;

void preorder(int i){
   if( A[i][0] != -1) preorder( A[i][0] );
   pre[ i ] = cnt++;
   if( A[i][1] != -1) preorder( A[i][1] );
   return;
}

void levelorder(){
   cnt = 0;
   queue< int > Q;
   Q.push( 0 );
   while( !Q.empty() ){
       int Size = Q.size();
       while( Size-- ){
          int i = Q.front();
          Q.pop();
          level[ cnt++ ] = i;
          if( A[i][0] != -1) Q.push( A[i][0] );
          if( A[i][1] != -1) Q.push( A[i][1] );
       }
   }
   return;
}



int main(){
   cin >> N;
   pre.resize( N );
   level.resize( N );
   v.resize(N);
   for(int i = 0; i < N; i++) cin >> A[i][0] >> A[i][1];
   cnt = 0;
   preorder( 0 );
   levelorder();
   for(int i = 0; i < N; i++) cin >> v[i];
   sort( v.begin(), v.end() );
   for(int i = 0; i < N; i++) {
      if( i ) putchar(' ');
      cout <<  v[ pre[ level[i] ] ];
   }
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1100 Mars Numbers(20 分)

People on Mars count their numbers with base 13:

  • Zero on Earth is called "tret" on Mars.
  • The numbers 1 to 12 on Earch is called "jan, feb, mar, apr, may, jun, jly, aug, sep, oct, nov, dec" on Mars, respectively.
  • For the next higher digit, Mars people name the 12 numbers as "tam, hel, maa, huh, tou, kes, hei, elo, syy, lok, mer, jou", respectively.

For examples, the number 29 on Earth is called "hel mar" on Mars; and "elo nov" on Mars corresponds to 115 on Earth. In order to help communication between people from these two planets, you are supposed to write a program for mutual translation between Earth and Mars number systems.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (<100). Then N lines follow, each contains a number in [0, 169), given either in the form of an Earth number, or that of Mars.

Output Specification:

For each number, print in a line the corresponding number in the other language.

Sample Input:

4
29
5
elo nov
tam

Sample Output:

hel mar
may
115
13

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 100000+10;
string a[13] = {"tret", "jan", "feb", "mar", "apr", "may", "jun", "jly", "aug", "sep", "oct", "nov", "dec"};
string b[13] = {"", "tam", "hel", "maa", "huh", "tou", "kes", "hei", "elo", "syy", "lok", "mer", "jou"};


int main(){
   int N;
   cin >> N;
   getchar();
   while( N-- ){
      string s;
      getline(cin, s);
      if( isdigit(s[0]) ){
         int u = stoi(s) / 13, v = stoi(s) % 13;
         if( u && v) cout << b[u] << " " << a[v] << endl;
         else if( u && !v) cout << b[u] << endl;
         else cout << a[v] << endl;
      }
      else{
         int ans = 0;
         stringstream ss(s);
         while( ss >> s){
            for(int i = 1; i < 13; i++) if( s == b[i]){
               ans += i*13;
            }
            for(int i = 0; i < 13; i++) if( s == a[i]){
               ans += i;
            }
         }
         cout << ans << endl;
      }
   }
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1101 Quick Sort(25 分)

There is a classical process named partition in the famous quick sort algorithm. In this process we typically choose one element as the pivot. Then the elements less than the pivot are moved to its left and those larger than the pivot to its right. Given N distinct positive integers after a run of partition, could you tell how many elements could be the selected pivot for this partition?

For example, given N=5 and the numbers 1, 3, 2, 4, and 5. We have:

  • 1 could be the pivot since there is no element to its left and all the elements to its right are larger than it;
  • 3 must not be the pivot since although all the elements to its left are smaller, the number 2 to its right is less than it as well;
  • 2 must not be the pivot since although all the elements to its right are larger, the number 3 to its left is larger than it as well;
  • and for the similar reason, 4 and 5 could also be the pivot.

Hence in total there are 3 pivot candidates.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤10​5​​). Then the next line contains N distinct positive integers no larger than 10​9​​. The numbers in a line are separated by spaces.

Output Specification:

For each test case, output in the first line the number of pivot candidates. Then in the next line print these candidates in increasing order. There must be exactly 1 space between two adjacent numbers, and no extra space at the end of each line.

Sample Input:

5
1 3 2 4 5

Sample Output:

3
1 4 5

 

 

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1e5+10;
int a[MAXN], b[MAXN];

int main(){
   int N;
   cin >> N;
   scanf("%d", &a[0]);
   b[0] = -1;
   for(int i = 1; i < N; i++){
      scanf("%d", &a[i]);
      b[i] = max( a[i-1], b[i-1] );
   }

   vector< int > ans;
   int k = 1e9+10;
   for(int i = N-1; i > 0; i--){
      if( a[i] > b[i] && a[i] < k) ans.push_back( a[i] );
      k = min( a[i], k);
   }
   if(a[0] < k) ans.push_back( a[0] );
   sort(ans.begin(), ans.end());
   cout << ans.size() << endl;
   for(int i = 0; i < ans.size(); i++){
      if( i ) putchar(' ');  
      cout << ans[i];
   }
   putchar('\n');
   return 0;
}

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1102 Invert a Binary Tree(25 分)

The following is from Max Howell @twitter:

Google: 90% of our engineers use the software you wrote (Homebrew), but you can't invert a binary tree on a whiteboard so fuck off.

Now it's your turn to prove that YOU CAN invert a binary tree!

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤10) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N−1. Then N lines follow, each corresponds to a node from 0 to N−1, and gives the indices of the left and right children of the node. If the child does not exist, a - will be put at the position. Any pair of children are separated by a space.

Output Specification:

For each test case, print in the first line the level-order, and then in the second line the in-order traversal sequences of the inverted tree. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.

Sample Input:

8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

Sample Output:

3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1e5+10;
vector< vector<int> > v;
int T = 0, N;

void levelorder(){
   int cnt = 0;
   queue< int > Q;
   Q.push(T);
   while( !Q.empty() ){
      int Size = Q.size();
      while( Size-- ){
         int t = Q.front();
         Q.pop();
         cout << t;
         if( ++cnt != N ) cout << " ";
         for(int i = 1; i >= 0; i--) if( v[t][i] != -1) Q.push( v[t][i] );
      }
   }
   cout << endl;
   return;
}

void inorder(int i){
   if( v[i][1] != -1 ) inorder( v[i][1] );
   cout << i;
   if(--N != 0) cout << " ";
   if( v[i][0] != -1 ) inorder( v[i][0] );
}

int main(){
   cin >> N;
   v.resize( N );
   vector< int > node(N, 0);
   for(int i = 0; i < N; i++){
      string s1, s2;
      cin >> s1 >> s2;
      v[i].push_back( s1[0] == '-' ? -1 : ( node [ stoi(s1) ] = 1, stoi(s1) ) );
      v[i].push_back( s2[0] == '-' ? -1 : ( node [ stoi(s2) ] = 1, stoi(s2) ) );
   }
   while( node[T] ) T++;
   levelorder();
   inorder(T);
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1103 Integer Factorization(30 分)

The K−PK-PK−P factorization of a positive integer NNN is to write NNN as the sum of the PPP-th power of KKK positive integers. You are supposed to write a program to find the K−PK-PK−P factorization of NNN for any positive integers NNN, KKK and PPP.

Input Specification:

Each input file contains one test case which gives in a line the three positive integers NNN (≤400\le 400≤400), KKK (≤N\le N≤N) and PPP (1<P≤71 < P\le 71<P≤7). The numbers in a line are separated by a space.

Output Specification:

For each case, if the solution exists, output in the format:

N = n[1]^P + ... n[K]^P

where n[i] (i = 1, ..., K) is the i-th factor. All the factors must be printed in non-increasing order.

Note: the solution may not be unique. For example, the 5-2 factorization of 169 has 9 solutions, such as 122+42+22+22+1212^2 + 4^2 + 2^2 + 2^2 + 1^212​2​​+4​2​​+2​2​​+2​2​​+1​2​​, or 112+62+22+22+2211^2 + 6^2 + 2^2 + 2^2 + 2^211​2​​+6​2​​+2​2​​+2​2​​+2​2​​, or more. You must output the one with the maximum sum of the factors. If there is a tie, the largest factor sequence must be chosen -- sequence { a1,a2,⋯,aKa_1, a_2, \cdots , a_Ka​1​​,a​2​​,⋯,a​K​​ } is said to be larger than { b1,b2,⋯,bKb_1, b_2, \cdots , b_Kb​1​​,b​2​​,⋯,b​K​​ } if there exists 1≤L≤K1\le L\le K1≤L≤K such that ai=bia_i=b_ia​i​​=b​i​​ for i<Li<Li<L and aL>bLa_L>b_La​L​​>b​L​​.

If there is no solution, simple output Impossible.

Sample Input 1:

169 5 2

Sample Output 1:

169 = 6^2 + 6^2 + 6^2 + 6^2 + 5^2

Sample Input 2:

169 167 3

Sample Output 2:

Impossible

 

#include<bits/stdc++.h>
using namespace std;

int n, k, p, maxFacSum = -1;
vector< int > v, ans, tempAns;

int POW(int i, int k){
    int res = i;
    while( --k ){
       res *= i;
    }
    return res;
}

void init() {
    scanf("%d%d%d", &n, &k, &p);
    int temp = 0, index = 1;
    while( temp <= n) {
        v.push_back(temp);
        temp = POW(index++, p);
    }
}

void dfs(int index, int tempSum, int tempK, int facSum) {
    if(tempSum == n && tempK == k) {
        if(facSum > maxFacSum) {
            ans = tempAns;
            maxFacSum = facSum;
        }
        return ;
    }
    if(tempSum > n || tempK > k) return ;
    if(index >= 1) {
        tempAns.push_back(index);
        dfs(index, tempSum + v[index], tempK + 1, facSum + index);
        tempAns.pop_back();
        dfs(index - 1, tempSum, tempK, facSum);
    }
}

int main() {
    init();
    dfs(v.size() - 1, 0, 0, 0);
    if(maxFacSum == -1)  printf("Impossible\n");
    else for(int i = 0; i < ans.size(); i++) {
          if( i ) printf(" + ");
          else printf("%d = ", n);
          printf("%d^%d", ans[i], p);
    }
    return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1104 Sum of Number Segments(20 分)

Given a sequence of positive numbers, a segment is defined to be a consecutive subsequence. For example, given the sequence { 0.1, 0.2, 0.3, 0.4 }, we have 10 segments: (0.1) (0.1, 0.2) (0.1, 0.2, 0.3) (0.1, 0.2, 0.3, 0.4) (0.2) (0.2, 0.3) (0.2, 0.3, 0.4) (0.3) (0.3, 0.4) and (0.4).

Now given a sequence, you are supposed to find the sum of all the numbers in all the segments. For the previous example, the sum of all the 10 segments is 0.1 + 0.3 + 0.6 + 1.0 + 0.2 + 0.5 + 0.9 + 0.3 + 0.7 + 0.4 = 5.0.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N, the size of the sequence which is no more than 10​5​​. The next line contains N positive numbers in the sequence, each no more than 1.0, separated by a space.

Output Specification:

For each test case, print in one line the sum of all the numbers in all the segments, accurate up to 2 decimal places.

Sample Input:

4
0.1 0.2 0.3 0.4

Sample Output:

5.00

 

 

#include <iostream>
using namespace std;
int main() {
    int n;
    cin >> n;
    double a, sum = 0.0;
    for (int i = 1; i <= n; i++) {
        cin >> a;
        sum += i *(n - i + 1)*a;
    }
    printf("%.2f", sum);
    return 0;
}

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1105 Spiral Matrix(25 分)

This time your job is to fill a sequence of N positive integers into a spiral matrix in non-increasing order. A spiral matrix is filled in from the first element at the upper-left corner, then move in a clockwise spiral. The matrix has m rows and n columns, where m and n satisfy the following: m×n must be equal to N; m≥n; and m−n is the minimum of all the possible values.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N. Then the next line contains N positive integers to be filled into the spiral matrix. All the numbers are no more than 10​4​​. The numbers in a line are separated by spaces.

Output Specification:

For each test case, output the resulting matrix in m lines, each contains n numbers. There must be exactly 1 space between two adjacent numbers, and no extra space at the end of each line.

Sample Input:

12
37 76 20 98 76 42 53 95 60 81 58 93

Sample Output:

98 95 93
42 37 81
53 20 76
58 60 76

 

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1000+5;
vector < int > v;
int a[MAXN][MAXN],N, x = 0, y = 0, i = 0;

void Print(int w1, int w2, int w3, int w4, int flag){
   if(i >= N-1) return;
   if(flag==1){
        while(x != w2) a[x++][y] = v[i++];
        Print(w1+1, w2, w3, w4,2);
   }
   else if(flag==2){
        while(y != w3) a[x][y++] = v[i++];
        Print(w1 ,w2-1, w3, w4,3);
   }
   else if(flag == 3){
        while(x != w4) a[x--][y] = v[i++];
        Print(w1, w2, w3-1, w4,4);
   }
   else{
        while(y != w1) a[x][y--] = v[i++];
        Print(w1, w2, w3, w4+1, 1);
   }
}

bool cmp(int a, int b){ return a > b; }

int main(){
   cin>>N;
   for(int i = 0; i < N; i++){
      int x;
      scanf("%d", &x);
      v.push_back(x);
   }
   sort(v.begin(), v.end(), cmp);
   int m, n = sqrt(N);
   while(1){
       if(N % n == 0){
          m = N / n;
          break;
       }
       n--;
   }
   Print(0, n-1, m-1, 0, 1);
   a[x][y] = v[i];
   for(int y = 0; y < m; y++)
     for(int x = 0;x < n; x++)
        cout << a[x][y] << ( (x == n-1)? '\n' : ' ');
   return 0;
}

 

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1106 Lowest Price in Supply Chain(25 分)

A supply chain is a network of retailers(零售商), distributors(经销商), and suppliers(供应商)-- everyone involved in moving a product from s

upplier to customer.

Starting from one root supplier, everyone on the chain buys products from one's supplier in a price P and sell or distribute them in a price that is r% higher than P. Only the retailers will face the customers. It is assumed that each member in the supply chain has exactly one supplier except the root supplier, and there is no supply cycle.

Now given a supply chain, you are supposed to tell the lowest price a customer can expect from some retailers.

Input Specification:

Each input file contains one test case. For each case, The first line contains three positive numbers: N (≤10​5​​), the total number of the members in the supply chain (and hence their ID's are numbered from 0 to N−1, and the root supplier's ID is 0); P, the price given by the root supplier; and r, the percentage rate of price increment for each distributor or retailer. Then N lines follow, each describes a distributor or retailer in the following format:

K​i​​ ID[1] ID[2] ... ID[K​i​​]

where in the i-th line, K​i​​ is the total number of distributors or retailers who receive products from supplier i, and is then followed by the ID's of these distributors or retailers. K​j​​ being 0 means that the j-th member is a retailer. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the lowest price we can expect from some retailers, accurate up to 4 decimal places, and the number of retailers that sell at the lowest price. There must be one space between the two numbers. It is guaranteed that the all the prices will not exceed 10​10​​.

Sample Input:

10 1.80 1.00
3 2 3 5
1 9
1 4
1 7
0
2 6 1
1 8
0
0
0

Sample Output:

1.8362 2

 

#include<bits/stdc++.h>
using namespace std;

double P, r;
int N, mindeep = 999999, sum;
vector< vector< int > >v;

void dfs(int i, int deep){
   if( v[i].empty() ){
     if( deep < mindeep){
        mindeep = deep;
        sum = 1;
     }
     else if( deep == mindeep) sum++;
     return;
   }
   for(auto &j : v[i]) dfs(j, deep+1);
}

int main(){
   cin >> N >> P >> r;
   r = r/100 + 1;
   v.resize(N);
   for(int i = 0; i < N; i++){
      int n, x;
      scanf("%d", &n);
      while( n-- ){
        scanf("%d", &x);
        v[i].push_back(x);
      }
   }
   dfs(0, 0);
   printf("%.4f %d\n", pow(r, mindeep)*P, sum);
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1107 Social Clusters(30 分)

When register on a social network, you are always asked to specify your hobbies in order to find some potential friends with the same hobbies. A social cluster is a set of people who have some of their hobbies in common. You are supposed to find all the clusters.

Input Specification:

Each input file contains one test case. For each test case, the first line contains a positive integer N (≤1000), the total number of people in a social network. Hence the people are numbered from 1 to N. Then N lines follow, each gives the hobby list of a person in the format:

K​i​​: h​i​​[1] h​i​​[2] ... h​i​​[K​i​​]

where K​i​​ (>0) is the number of hobbies, and h​i​​[j] is the index of the j-th hobby, which is an integer in [1, 1000].

Output Specification:

For each case, print in one line the total number of clusters in the network. Then in the second line, print the numbers of people in the clusters in non-increasing order. The numbers must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:

8
3: 2 7 10
1: 4
2: 5 3
1: 4
1: 3
1: 4
4: 6 8 1 5
1: 4

Sample Output:

3
4 3 1

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1000+5;
int a[MAXN], fa[MAXN];
int N;

int findfa( int x ){
   return  x == fa[x]  ?  x : x = findfa( fa[x] ) ;
}

void Union(int x, int father){
   fa[ findfa(x) ] = father;
}

int main(){
   cin >> N;
   for(int i = 1; i <= N; i++) fa[i] = i;
   for(int i = 1; i <= N; i++){
      int n, x;
      scanf("%d:", &n);
      int father = findfa(i);
      while( n-- ){
        scanf("%d", &x);
        if( !a[x] ) a[x] = i;
        Union(a[x], father);
      }
   }
   map <int, int> Mymap;
   for(int i = 1; i <= N; i++)   Mymap[ findfa(i) ]++;
   vector< int > ans;
   for(auto &i : Mymap) ans.push_back( i.second );
   sort(ans.begin(), ans.end() );
   cout << ans.size() << endl;

   for(int i = ans.size()-1; i >= 0; i--){
      printf("%d%c", ans[i], ( i ? ' ': '\n' ) );
   }
   return 0;
}

 

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1108 Finding Average(20 分)

The basic task is simple: given N real numbers, you are supposed to calculate their average. But what makes it complicated is that some of the input numbers might not be legal. A legal input is a real number in [−1000,1000] and is accurate up to no more than 2 decimal places. When you calculate the average, those illegal numbers must not be counted in.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤100). Then N numbers are given in the next line, separated by one space.

Output Specification:

For each illegal input number, print in a line ERROR: X is not a legal number where X is the input. Then finally print in a line the result: The average of K numbers is Y where K is the number of legal inputs and Y is their average, accurate to 2 decimal places. In case the average cannot be calculated, output Undefined instead of Y. In case K is only 1, output The average of 1 number is Y instead.

Sample Input 1:

7
5 -3.2 aaa 9999 2.3.4 7.123 2.35

Sample Output 1:

ERROR: aaa is not a legal number
ERROR: 9999 is not a legal number
ERROR: 2.3.4 is not a legal number
ERROR: 7.123 is not a legal number
The average of 3 numbers is 1.38

Sample Input 2:

2
aaa -9999

Sample Output 2:

ERROR: aaa is not a legal number
ERROR: -9999 is not a legal number
The average of 0 numbers is Undefined

 

#include<bits/stdc++.h>
using namespace std;

int main(){
   int N, cnt = 0;
   double sum = 0.0;
   cin >> N;
   while( N-- ){
      string s;
      cin >> s;
      int flag = 1, ok = 1;
      for(int i = 0; i < s.length() && ok; i++){
         if( !isdigit(s[i]) && s[i] != '.' && s[i] != '-' )  ok = 0;
         if( flag && s[i] == '.')  {
            flag = 0;
            if( s.length() - i > 3)  ok = 0;
         }
         else if( !flag && s[i] == '.') ok = 0;
      }
      if( ok && fabs( stof(s) ) <= 1000 ) {sum += stof(s); cnt++; }
      else printf("ERROR: %s is not a legal number\n", s.c_str() );
   }
   if( !cnt ) printf("The average of 0 numbers is Undefined\n");
   else printf("The average of %d number%sis %.2f\n", cnt, (cnt == 1 ? " " : "s "), sum/cnt);
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1109 Group Photo(25 分)

Formation is very important when taking a group photo. Given the rules of forming K rows with N people as the following:

  • The number of people in each row must be N/K (round down to the nearest integer), with all the extra people (if any) standing in the last row;

  • All the people in the rear row must be no shorter than anyone standing in the front rows;

  • In each row, the tallest one stands at the central position (which is defined to be the position (m/2+1), where m is the total number of people in that row, and the division result must be rounded down to the nearest integer);

  • In each row, other people must enter the row in non-increasing order of their heights, alternately taking their positions first to the right and then to the left of the tallest one (For example, given five people with their heights 190, 188, 186, 175, and 170, the final formation would be 175, 188, 190, 186, and 170. Here we assume that you are facing the group so your left-hand side is the right-hand side of the one at the central position.);

  • When there are many people having the same height, they must be ordered in alphabetical (increasing) order of their names, and it is guaranteed that there is no duplication of names.

Now given the information of a group of people, you are supposed to write a program to output their formation.

Input Specification:

Each input file contains one test case. For each test case, the first line contains two positive integers N (≤10​4​​), the total number of people, and K (≤10), the total number of rows. Then N lines follow, each gives the name of a person (no more than 8 English letters without space) and his/her height (an integer in [30, 300]).

Output Specification:

For each case, print the formation -- that is, print the names of people in K lines. The names must be separated by exactly one space, but there must be no extra space at the end of each line. Note: since you are facing the group, people in the rear rows must be printed above the people in the front rows.

Sample Input:

10 3
Tom 188
Mike 170
Eva 168
Tim 160
Joe 190
Ann 168
Bob 175
Nick 186
Amy 160
John 159

Sample Output:

Bob Tom Joe Nick
Ann Mike Eva
Tim Amy John

 

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1e4+10;
int N, M, K;
struct node{
   char name[10];
   int height;
   bool operator < (const node &rhs) const{
      return (height == rhs.height) ? (strcmp(name, rhs.name) < 0) : height > rhs.height;
   }
} a[MAXN];

int main(){
   cin >> N >> K;
   M = N/K;
   for(int i = 0; i < N; i++)
      scanf("%s%d", a[i].name, &a[i].height);
   sort(a, a+N);
   int p = 0, q = N - M*K + M;
   while(q <= N){
      deque< node > Q;
      for(int i = p, k = 1; i < q; i++, k ^= 1){
         if(k) Q.push_back( a[i] );
         else Q.push_front( a[i] );
      }
      int flag = 0;
      while( !Q.empty() ){
         if( flag ) putchar(' ');
         else flag = 1;
         printf("%s", Q.front().name );
         Q.pop_front();
      }
      putchar('\n');
      p = q;
      q = p+M;
   }
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1110 Complete Binary Tree(25 分)

Given a tree, you are supposed to tell if it is a complete binary tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤20) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N−1. Then N lines follow, each corresponds to a node, and gives the indices of the left and right children of the node. If the child does not exist, a - will be put at the position. Any pair of children are separated by a space.

Output Specification:

For each case, print in one line YES and the index of the last node if the tree is a complete binary tree, or NO and the index of the root if not. There must be exactly one space separating the word and the number.

Sample Input 1:

9
7 8
- -
- -
- -
0 1
2 3
4 5
- -
- -

Sample Output 1:

YES 8

Sample Input 2:

8
- -
4 5
0 6
- -
2 3
- 7
- -
- -

Sample Output 2:

NO 1

 

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1e4+10;
int N, T = 0, LAST;
vector< vector< int > > v;

bool levelorder( int T ){
   queue< int > Q;
   Q.push( T );
   int flag = 1;
   while( !Q.empty() ){
      int Size = Q.size();
      while( Size-- ){
         vector< int > &t = v[ LAST = Q.front() ];
         Q.pop();
         if( t[0] != -1 && t[1] != -1 ){
            if( !flag ) return false;
            Q.push( t[0] ); Q.push( t[1] );
         }
         else if( t[0] != -1){
            if( !flag ) return false;
            Q.push( t[0] );
            flag = 0;
         }
         else if( t[1] != -1)  return false;
         else flag = 0;
      }
   }
   return true;
}

int main(){
   cin >> N;
   v.resize( N );
   vector< int > node(N, 0);
   for(int i = 0; i < N; i++){
       string l, r;
       cin >> l >> r;
       v[i].push_back(  l[0] == '-' ?  -1 : ( node[ stoi(l) ] = 1, stoi(l)  ) );
       v[i].push_back(  r[0] == '-' ?  -1 : ( node[ stoi(r) ] = 1, stoi(r)  ) );
   }
   while( node[T] ) T++;
   if( levelorder( T ) ) printf("YES %d\n", LAST);
   else printf("NO %d\n", T);
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1111 Online Map(30 分)

Input our current position and a destination, an online map can recommend several paths. Now your job is to recommend two paths to your user: one is the shortest, and the other is the fastest. It is guaranteed that a path exists for any request.

Input Specification:

Each input file contains one test case. For each case, the first line gives two positive integers N (2≤N≤500), and M, being the total number of streets intersections on a map, and the number of streets, respectively. Then M lines follow, each describes a street in the format:

V1 V2 one-way length time

where V1 and V2 are the indices (from 0 to N−1) of the two ends of the street; one-way is 1 if the street is one-way from V1 to V2, or 0 if not; length is the length of the street; and time is the time taken to pass the street.

Finally a pair of source and destination is given.

Output Specification:

For each case, first print the shortest path from the source to the destination with distance D in the format:

Distance = D: source -> v1 -> ... -> destination

Then in the next line print the fastest path with total time T:

Time = T: source -> w1 -> ... -> destination

In case the shortest path is not unique, output the fastest one among the shortest paths, which is guaranteed to be unique. In case the fastest path is not unique, output the one that passes through the fewest intersections, which is guaranteed to be unique.

In case the shortest and the fastest paths are identical, print them in one line in the format:

Distance = D; Time = T: source -> u1 -> ... -> destination

Sample Input 1:

10 15
0 1 0 1 1
8 0 0 1 1
4 8 1 1 1
3 4 0 3 2
3 9 1 4 1
0 6 0 1 1
7 5 1 2 1
8 5 1 2 1
2 3 0 2 2
2 1 1 1 1
1 3 0 3 1
1 4 0 1 1
9 7 1 3 1
5 1 0 5 2
6 5 1 1 2
3 5

Sample Output 1:

Distance = 6: 3 -> 4 -> 8 -> 5
Time = 3: 3 -> 1 -> 5

Sample Input 2:

7 9
0 4 1 1 1
1 6 1 1 3
2 6 1 1 1
2 5 1 2 2
3 0 0 1 1
3 1 1 1 3
3 2 1 1 2
4 5 0 2 2
6 5 1 1 2
3 5

Sample Output 2:

Distance = 3; Time = 4: 3 -> 2 -> 5

 

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 505, INF = 99999999;
int d[2][MAXN][MAXN];
int dist[2][MAXN], v[MAXN], path[MAXN];
int City[MAXN], T[MAXN];
int N, M, C, S;
vector< int > ans[2];

void Dijkstra( int k ){
   dist[k][C] = 0;
   memset(v, 0, sizeof(v));
   memset(City, 0, sizeof(City));
   memset(T, 0, sizeof(T));
   for(int i = 0; i < N; i++){
      int minn = INF, x = -1;
      for(int y = 0; y < N; y++) if( !v[y] && dist[k][y] < minn){
         minn = dist[k][ x = y];
      }
      if( x < 0) break;
      v[x] = 1;
      for(int y = 0; y < N; y++) if( !v[y] && d[k][x][y] ){
         if(dist[k][y] > dist[k][x] + d[k][x][y]){
            dist[k][y] = dist[k][x] + d[k][x][y];
            path[y] = x;
            City[y] = City[x]+1;
            T[y] = T[x]+d[1][x][y];
         }
         else if(dist[k][y] == dist[k][x] + d[k][x][y]){
            if( (!k && T[y] > T[x]+d[1][x][y] ) || ( k && City[y] > City[x]+1) ){
               path[y] = x;
               T[y] = T[x]+d[1][x][y];
               City[y] = City[x]+1;
            }
         }
      }
   }
}

void print( int k ){
   vector< int > &v = ans[k];
   for(int i = v.size()-1; i >= 0; i--){
        cout << v[i];
        if( i ) cout << " -> ";
        else cout << endl;
   }
   return ;
}

int main(){
   cin >> N >> M;
   while( M-- ){
      int V1, V2, one_way, length, Time;
      scanf("%d%d%d%d%d", &V1, &V2, &one_way, &length, &Time);
      d[0][ V1 ][ V2 ] = length;
      d[1][ V1 ][ V2 ] = Time;
      if( !one_way ) {
         d[0][ V2 ][ V1 ] = length;
         d[1][ V2 ][ V1 ] = Time;
      }
   }
   scanf("%d%d", &C, &S);
   fill(dist[0], dist[0]+2*MAXN, INF);
   for(int k = 0; k < 2; k++){
      Dijkstra( k );
      for(int i = S; i != C; i = path[i]) ans[k].push_back(i);
      ans[k].push_back(C);
   }
   if( ans[0] == ans[1] ){
       printf("Distance = %d; Time = %d: ", dist[0][S], dist[1][S]);
       print(0);
   }
   else{
       printf("Distance = %d: ", dist[0][S]);  print(0);
       printf("Time = %d: ", dist[1][S]);  print(1);
   }
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1112 Stucked Keyboard(20 分)

On a broken keyboard, some of the keys are always stucked. So when you type some sentences, the characters corresponding to those keys will appear repeatedly on screen for k times.

Now given a resulting string on screen, you are supposed to list all the possible stucked keys, and the original string.

Notice that there might be some characters that are typed repeatedly. The stucked key will always repeat output for a fixed k times whenever it is pressed. For example, when k=3, from the string thiiis iiisss a teeeeeest we know that the keys i and e might be stucked, but s is not even though it appears repeatedly sometimes. The original string could be this isss a teest.

Input Specification:

Each input file contains one test case. For each case, the 1st line gives a positive integer k (1<k≤100) which is the output repeating times of a stucked key. The 2nd line contains the resulting string on screen, which consists of no more than 1000 characters from {a-z}, {0-9} and _. It is guaranteed that the string is non-empty.

Output Specification:

For each test case, print in one line the possible stucked keys, in the order of being detected. Make sure that each key is printed once only. Then in the next line print the original string. It is guaranteed that there is at least one stucked key.

Sample Input:

3
caseee1__thiiis_iiisss_a_teeeeeest

Sample Output:

ei
case1__this_isss_a_teest

 

 

 

#include<bits/stdc++.h>
using namespace std;

unordered_set< char > Wrong, Right, Printed;

int main(){
   string s;
   int K, len;
   cin >> K >> s;
   len = s.length();
   for(int i = 0; i < len; i++){
      int j =  i, ok = 1;
      for(; j < len && j < i+K; j++)
          if( s[j] != s[i] ) ok = 0;
      if( ok && j == i+K && !Right.count(s[i]) ){
         Wrong.insert( s[i] );
         i = j-1;
      }
      else{
         if( Wrong.count(s[i]) )Wrong.erase( s[i] );
         Right.insert( s[i] );
      }
   }
   for(auto &i : s) if( Wrong.count(i) && !Printed.count(i)) {
       cout << i;
       Printed.insert(i);
   }
   putchar('\n');
   for(int i = 0; i < len; i++){
      cout << s[i];
      if( Wrong.count( s[i] ) ) i = i+K-1;
   }
   return 0;
}

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1113 Integer Set Partition(25 分)

Given a set of NNN (>1> 1>1) positive integers, you are supposed to partition them into two disjoint sets A1A_1A​1​​ and A2A_2A​2​​ of n1n_1n​1​​ and n2n_2n​2​​ numbers, respectively. Let S1S_1S​1​​ and S2S_2S​2​​ denote the sums of all the numbers in A1A_1A​1​​ and A2A_2A​2​​, respectively. You are supposed to make the partition so that ∣n1−n2∣|n_1 - n_2|∣n​1​​−n​2​​∣ is minimized first, and then ∣S1−S2∣|S_1 - S_2|∣S​1​​−S​2​​∣ is maximized.

Input Specification:

Each input file contains one test case. For each case, the first line gives an integer NNN (2≤N≤1052 \le N \le 10^52≤N≤10​5​​), and then NNN positive integers follow in the next line, separated by spaces. It is guaranteed that all the integers and their sum are less than 2312^{31}2​31​​.

Output Specification:

For each case, print in a line two numbers: ∣n1−n2∣|n_1 - n_2|∣n​1​​−n​2​​∣ and ∣S1−S2∣|S_1 - S_2|∣S​1​​−S​2​​∣, separated by exactly one space.

Sample Input 1:

10
23 8 10 99 46 2333 46 1 666 555

Sample Output 1:

0 3611

Sample Input 2:

13
110 79 218 69 3721 100 29 135 2 6 13 5188 85

Sample Output 2:

1 9359

 

#include<bits/stdc++.h>
using namespace std;


int main(){
   int N, n, sum = 0, x;
   cin >> N;
   n = N/2;
   vector< int > v(N+1);
   for(int i = 1; i <= N; i++) scanf("%d", &v[i]);
   sort( v.begin()+1, v.end() );
   for(int i = 1; i <= N; i++){
	  if( i <= n) sum -= v[i];
   	  else sum += v[i];
   }
   printf("%d %d\n", N%2, sum);
   return 0;
}

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1114 Family Property(25 分)

This time, you are supposed to help us collect the data for family-owned property. Given each person's family members, and the estate(房产)info under his/her own name, we need to know the size of each family, and the average area and number of sets of their real estate.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer NNN (≤1000\le 1000≤1000). Then NNN lines follow, each gives the infomation of a person who owns estate in the format:

ID Father Mother kkk Child1⋯ChildkChild_1 \cdots Child_kChild​1​​⋯Child​k​​ MestateM_{estate}M​estate​​ Area

where ID is a unique 4-digit identification number for each person; Father and Mother are the ID's of this person's parents (if a parent has passed away, -1 will be given instead); kkk (0≤k≤50\le k\le 50≤k≤5) is the number of children of this person; ChildiChild_iChild​i​​'s are the ID's of his/her children; MestateM_{estate}M​estate​​ is the total number of sets of the real estate under his/her name; and Area is the total area of his/her estate.

Output Specification:

For each case, first print in a line the number of families (all the people that are related directly or indirectly are considered in the same family). Then output the family info in the format:

ID M AVGsetsAVG_{sets}AVG​sets​​ AVGareaAVG_{area}AVG​area​​

where ID is the smallest ID in the family; M is the total number of family members; AVGsetsAVG_{sets}AVG​sets​​ is the average number of sets of their real estate; and AVGareaAVG_{area}AVG​area​​ is the average area. The average numbers must be accurate up to 3 decimal places. The families must be given in descending order of their average areas, and in ascending order of the ID's if there is a tie.

Sample Input:

10
6666 5551 5552 1 7777 1 100
1234 5678 9012 1 0002 2 300
8888 -1 -1 0 1 1000
2468 0001 0004 1 2222 1 500
7777 6666 -1 0 2 300
3721 -1 -1 1 2333 2 150
9012 -1 -1 3 1236 1235 1234 1 100
1235 5678 9012 0 1 50
2222 1236 2468 2 6661 6662 1 300
2333 -1 3721 3 6661 6662 6663 1 100

Sample Output:

3
8888 1 1.000 1000.000
0001 15 0.600 100.000
5551 4 0.750 100.000
#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1e4 + 5;
int N;
int fa[MAXN];
bool book[MAXN];


int find( int x ){
   return (x == fa[x]) ? x : (fa[x] = find( fa[x] ));
}


void Union(int x, int y){
   book[y] = true;
   fa[ find(y) ] = x;
}

struct node{
   int estate, Area;
   int cnt, id;
   bool operator < (const node &rhs ) const {
      if( Area*rhs.cnt != rhs.Area*cnt ) return Area*rhs.cnt > rhs.Area*cnt;
      return id < rhs.id;
   }
}family[MAXN], Ans[MAXN];

int main(){
   for(int i = 0; i <= MAXN; i++) fa[i] = i;
   cin >> N;
   for(int i = 0; i < N; i++){
      int ID, Father, Mother, k, Child, estate, Area;
      scanf("%d%d%d%d", &ID, &Father, &Mother, &k);
      book[ID] = true;
      ID = find(ID);
      if( Father != -1 ) Union(ID, Father);
      if( Mother != -1 ) Union(ID, Mother);
      while( k-- ){
         scanf("%d", &Child);
         Union(ID, Child);
      }
      scanf("%d%d", &estate, &Area);
      family[ID].estate += estate;
      family[ID].Area += Area;
   }
   
   map<int, int> Mymap;
   int cnt = 0;
   for(int i = 0; i < MAXN; i++) if( book[i] ){
      int fa = find(i);
      if( Mymap.find(fa) == Mymap.end() )   Mymap[fa] = cnt++;
      int t = Mymap[fa];
      Ans[t].estate += family[i].estate;
      Ans[t].Area += family[i].Area;
      Ans[t].id = (Ans[t].cnt == 0 ) ? i : min(i, Ans[t].id);
      Ans[t].cnt++;
   }
   
   sort(Ans, Ans+cnt);
   cout << cnt << endl;
   for(int i = 0; i < cnt; i++)
      printf("%04d %d %.3f %.3f\n", Ans[i].id, Ans[i].cnt, Ans[i].estate*1.0/Ans[i].cnt, Ans[i].Area*1.0/Ans[i].cnt);
   return 0;
}

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1115 Counting Nodes in a BST(30 分)

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:

  • The left subtree of a node contains only nodes with keys less than or equal to the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

Insert a sequence of numbers into an initially empty binary search tree. Then you are supposed to count the total number of nodes in the lowest 2 levels of the resulting tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤1000) which is the size of the input sequence. Then given in the next line are the N integers in [−10001000] which are supposed to be inserted into an initially empty binary search tree.

Output Specification:

For each case, print in one line the numbers of nodes in the lowest 2 levels of the resulting tree in the format:

n1 + n2 = n

where n1 is the number of nodes in the lowest level, n2 is that of the level above, and n is the sum.

Sample Input:

9
25 30 42 16 20 20 35 -5 28

Sample Output:

2 + 4 = 6

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1e3 + 5;
int maxheight = 0, Height[MAXN];

typedef struct node{
   int value,height;
   struct node *left,*right;
} *Node;

Node build(Node root, int a, int h){
    if(root == NULL){
        root = new struct node();
        root->left = root->right = NULL;
        root->value = a;
        root->height = h;
        Height[h]++;
        maxheight = max(h, maxheight);
    }
    else if(a <= root->value ) root->left = build( root->left, a, h+1);
    else root->right = build( root->right, a, h+1);
    return root;
}

int main(){
    int n,a;
    cin >> n;
    Node root = NULL;
    for(int i = 0; i < n; i++){
        cin >> a;
        root = build(root, a, 0);
    }
    cout << Height[maxheight] << " + " << Height[maxheight-1] << " = " << Height[maxheight]+Height[maxheight-1] << endl;
    return 0;
}
#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1e3 + 5;
int N, maxdeep = 0;
vector< int > v, height(MAXN);
int T[MAXN][2];
bool book[MAXN][2];


void build(int i, int id, int x, int deep){
	maxdeep = max( deep, maxdeep );
	height[deep]++;
	if(x <= v[i]){
   	   if( !book[i][0] ){
   		book[i][0] = true;
 		T[i][0] = id; 
   	   }
   	   else build( T[i][0], id, x, deep+1);
   	}
   	else{
   	   if( !book[i][1] ){
   		book[i][1] = true;
   		T[i][1] = id; 
   	   }
   	   else build( T[i][1], id, x, deep+1);
   	}
}




int main(){
   scanf("%d", &N);
   v.resize(N);
   for(int i = 0; i < N; i++){
      scanf("%d", &v[i]);
      if(i) build(0, i, v[i], 0);
   }
   if(N == 1) cout << "1 + 0 = 1\n";
   else printf("%d + %d = %d\n", height[maxdeep], height[maxdeep-1]-height[maxdeep], height[maxdeep-1]);
   return 0;
}

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1116 Come on! Let's C(20 分)

"Let's C" is a popular and fun programming contest hosted by the College of Computer Science and Technology, Zhejiang University. Since the idea of the contest is for fun, the award rules are funny as the following:

  • 0、 The Champion will receive a "Mystery Award" (such as a BIG collection of students' research papers...).
  • 1、 Those who ranked as a prime number will receive the best award -- the Minions (小黄人)!
  • 2、 Everyone else will receive chocolates.

Given the final ranklist and a sequence of contestant ID's, you are supposed to tell the corresponding awards.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤10​4​​), the total number of contestants. Then N lines of the ranklist follow, each in order gives a contestant's ID (a 4-digit number). After the ranklist, there is a positive integer K followed by K query ID's.

Output Specification:

For each query, print in a line ID: award where the award is Mystery Award, or Minion, or Chocolate. If the ID is not in the ranklist, print Are you kidding? instead. If the ID has been checked before, print ID: Checked.

Sample Input:

6
1111
6666
8888
1234
5555
0001
6
8888
0001
1111
2222
8888
2222

Sample Output:

8888: Minion
0001: Chocolate
1111: Mystery Award
2222: Are you kidding?
8888: Checked
2222: Are you kidding?

 

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1e4+10;

bool isprime( int n ){
   if( n == 1) return false;
   for(int i = 2; i <= sqrt(n)+0.5; i++)
      if( n % i == 0) return true;
   return false;
}

int a[MAXN];

int main(){
   int N, K;
   cin >> N;
   for(int i = 1; i <= N; i++){
      int x;
      scanf("%d", &x);
      a[x] = (i != 1 ? i : -1);
   }
   cin >> K;
   set < int > checked;
   while( K-- ){
      int x;
      scanf("%d", &x);
      if( !a[x] ) printf("%04d: Are you kidding?\n", x);
      else if( checked.count(x) ) printf("%04d: Checked\n", x);
      else{
          if( a[x] == -1) printf("%04d: Mystery Award\n", x);
          else if( !isprime( a[x] ) ) printf("%04d: Minion\n", x);
          else printf("%04d: Chocolate\n", x);
          checked.insert(x);
      }
   }
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1117 Eddington Number(25 分)

British astronomer Eddington liked to ride a bike. It is said that in order to show off his skill, he has even defined an "Eddington number", E -- that is, the maximum integer E such that it is for E days that one rides more than E miles. Eddington's own E was 87.

Now given everyday's distances that one rides for N days, you are supposed to find the corresponding E (≤N).

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤10​5​​), the days of continuous riding. Then N non-negative integers are given in the next line, being the riding distances of everyday.

Output Specification:

For each case, print in a line the Eddington number for these N days.

Sample Input:

10
6 7 6 9 3 10 8 2 7 8

Sample Output:

6

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 2e5+10;
int a[MAXN];

int main(){
   int N;
   cin >> N;
   for(int i = 0; i < N; i++){
      int x;
      scanf("%d", &x);
      a[x]++;
   }
   int cnt = 0;
   for(int i = MAXN-1;; i--){
      if( cnt >= i ){
         cout << i << endl;
         break;
      }
      cnt += a[i];
   }
   return 0;
}

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1118 Birds in Forest(25 分)

Some scientists took pictures of thousands of birds in a forest. Assume that all the birds appear in the same picture belong to the same tree. You are supposed to help the scientists to count the maximum number of trees in the forest, and for any pair of birds, tell if they are on the same tree.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive number N (≤10​4​​) which is the number of pictures. Then N lines follow, each describes a picture in the format:

K B​1​​ B​2​​ ... B​K​​

where K is the number of birds in this picture, and B​i​​'s are the indices of birds. It is guaranteed that the birds in all the pictures are numbered continuously from 1 to some number that is no more than 104.

After the pictures there is a positive number Q (≤10​4​​) which is the number of queries. Then Q lines follow, each contains the indices of two birds.

Output Specification:

For each test case, first output in a line the maximum possible number of trees and the number of birds. Then for each query, print in a line Yes if the two birds belong to the same tree, or No if not.

Sample Input:

4
3 10 1 2
2 3 4
4 1 5 7 8
3 9 6 4
2
10 5
3 7

Sample Output:

2 10
Yes
No
#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1e4+10;
int fa[MAXN], MAX = 1;
unordered_set< int >  Set;


int findfa( int x){
   return x == fa[x] ? x : (fa[x] = findfa(fa[x]) );
}

int main(){
   int N, Q;
   cin >> N;
   for( int i = 0; i < MAXN; i++) fa[i] = i;
   for(int i = 0; i < N; i++){
      int n, x, y;
      scanf("%d %d", &n, &x);
      MAX = max(MAX, x);
      x = findfa(x);
      while( --n ){
         scanf("%d", &y);
         MAX = max(MAX, y);
         y = findfa(y);
         fa[y] = x;
      }
   }
   for(int i = 1; i <= MAX; i++) Set.insert( findfa(i) );
   cin >> Q;
   cout << Set.size() << " " << MAX << endl;
   while( Q-- ){
      int x, y;
      scanf("%d%d", &x,&y);
      if(fa[x] == fa[y] ) cout << "Yes\n";
      else cout << "No\n";
   }
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1119 Pre- and Post-order Traversals(30 分)

Suppose that all the keys in a binary tree are distinct positive integers. A unique binary tree can be determined by a given pair of postorder and inorder traversal sequences, or preorder and inorder traversal sequences. However, if only the postorder and preorder traversal sequences are given, the corresponding tree may no longer be unique.

Now given a pair of postorder and preorder traversal sequences, you are supposed to output the corresponding inorder traversal sequence of the tree. If the tree is not unique, simply output any one of them.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤ 30), the total number of nodes in the binary tree. The second line gives the preorder sequence and the third line gives the postorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, first printf in a line Yes if the tree is unique, or No if not. Then print in the next line the inorder traversal sequence of the corresponding binary tree. If the solution is not unique, any answer would do. It is guaranteed that at least one solution exists. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input 1:

7
1 2 3 4 6 7 5
2 6 7 4 5 3 1

Sample Output 1:

Yes
2 1 6 4 7 3 5

Sample Input 2:

4
1 2 3 4
2 4 3 1

Sample Output 2:

No
2 1 3 4

 

 

#include<bits/stdc++.h>
using namespace std;

vector <int> pre, post, in;
bool Unique = true;

void inorder(int prel, int prer, int postl, int postr){
   if(prel > prer) return;
   if(prel == prer){
      in.push_back(pre[prel]);
      return;
   }
   int i = prel+1;
   while( pre[i] != post[postr-1] ) i++;
   if(i-prel == 1) Unique = false;
   inorder(prel+1, i-1, postl, i-2-prel+postl);
   in.push_back( post[postr] );
   inorder(i, prer, i-1-prel+postl, postr-1);
}

int main(){
    int n;
    cin >> n;
    pre.resize(n);
    post.resize(n);
    for(int i = 0; i < n; i++) cin >> pre[i];
    for(int i = 0; i < n; i++) cin >> post[i];
    inorder(0, n-1, 0, n-1);
    printf("%s\n%d", Unique ? "Yes" : "No", in[0]);
    for(int i = 1; i < in.size(); i++)
        cout << " " << in[i];
    putchar('\n');
    return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1120 Friend Numbers(20 分)

Two integers are called "friend numbers" if they share the same sum of their digits, and the sum is their "friend ID". For example, 123 and 51 are friend numbers since 1+2+3 = 5+1 = 6, and 6 is their friend ID. Given some numbers, you are supposed to count the number of different frind ID's among them.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N. Then N positive integers are given in the next line, separated by spaces. All the numbers are less than 10​4​​.

Output Specification:

For each case, print in the first line the number of different frind ID's among the given integers. Then in the second line, output the friend ID's in increasing order. The numbers must be separated by exactly one space and there must be no extra space at the end of the line.

Sample Input:

8
123 899 51 998 27 33 36 12

Sample Output:

4
3 6 9 26
#include<bits/stdc++.h>
using namespace std;

int main(){
   int N, cnt = 0;
   set< int > Myset;
   cin >> N;
   while( N-- ){
      string s;
      cin >> s;
      int sum = 0;
      for(auto i : s) sum += int(i -'0');
      Myset.insert( sum );
   }
   cout << Myset.size() << endl;
   for(auto i : Myset){
      if( cnt++ ) putchar(' '); 
      cout << i;
   }
   return 0;
}

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1121 Damn Single(25 分)

"Damn Single (单身狗)" is the Chinese nickname for someone who is being single. You are supposed to find those who are alone in a big party, so they can be taken care of.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤ 50,000), the total number of couples. Then N lines of the couples follow, each gives a couple of ID's which are 5-digit numbers (i.e. from 00000 to 99999). After the list of couples, there is a positive integer M (≤ 10,000) followed by M ID's of the party guests. The numbers are separated by spaces. It is guaranteed that nobody is having bigamous marriage (重婚) or dangling with more than one companion.

Output Specification:

First print in a line the total number of lonely guests. Then in the next line, print their ID's in increasing order. The numbers must be separated by exactly 1 space, and there must be no extra space at the end of the line.

Sample Input:

3
11111 22222
33333 44444
55555 66666
7
55555 44444 10000 88888 22222 11111 23333

Sample Output:

5
10000 23333 44444 55555 88888

 

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1e5+10;
int book[MAXN];

int main(){
   fill(book, book+MAXN, -1);   
   int N, M;
   cin >> N;
   while( N-- ){
      int x, y;
      scanf("%d%d", &x, &y);
      book[x] = y;
      book[y] = x;
   }
   cin >> M;
   set < int > Myset;
   while( M-- ){
      int x;
      scanf("%d", &x);
      if( book[x] != -1 && Myset.find( book[x] ) != Myset.end() ) Myset.erase( book[x] );
      else Myset.insert(x);
   }
   cout << Myset.size() << endl;
   int cnt = 0;
   for(auto i : Myset){
      if( cnt++ ) putchar(' ');
      printf("%05d", i);
   }
   return 0;
}

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1122 Hamiltonian Cycle(25 分)

The "Hamilton cycle problem" is to find a simple cycle that contains every vertex in a graph. Such a cycle is called a "Hamiltonian cycle".

In this problem, you are supposed to tell if a given cycle is a Hamiltonian cycle.

Input Specification:

Each input file contains one test case. For each case, the first line contains 2 positive integers N (2<N≤200), the number of vertices, and M, the number of edges in an undirected graph. Then M lines follow, each describes an edge in the format Vertex1 Vertex2, where the vertices are numbered from 1 to N. The next line gives a positive integer K which is the number of queries, followed by K lines of queries, each in the format:

n V​1​​ V​2​​ ... V​n​​

where n is the number of vertices in the list, and V​i​​'s are the vertices on a path.

Output Specification:

For each query, print in a line YES if the path does form a Hamiltonian cycle, or NO if not.

Sample Input:

6 10
6 2
3 4
1 5
2 5
3 1
4 1
1 6
6 3
1 2
4 5
6
7 5 1 4 3 6 2 5
6 5 1 4 3 6 2
9 6 2 1 6 3 4 5 2 6
4 1 2 5 1
7 6 1 3 4 5 2 6
7 6 1 2 5 4 3 1

Sample Output:

YES
NO
NO
NO
YES
NO

 

 

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 2e2+10;

int N, M, Q;
bool d[MAXN][MAXN];

int main(){
   cin >> N >> M;
   while( M-- ){
      int x, y;
      scanf("%d%d", &x, &y);
      d[y][x] = d[x][y] = true;
   }
   cin >> Q;
   while( Q-- ){
      int n;
      bool ok = true;
      scanf("%d", &n);
      vector< int > v(n);
      for(int i = 0; i < n; i++) scanf("%d", &v[i]);
      if( n != N+1 || v[0] != v[n-1]) ok = false;
      else{
         vector< int > temp = v;
         temp.resize(N);
         sort(temp.begin(), temp.end() );
         for(int i = 0; i < N; i++) if( temp[i] != i+1){
            ok = false; break;
         }
         if(ok){
            for(int i = 0; i < N; i++) if( !d[ v[i] ][ v[i+1] ]  ){
               ok = false; break;
            }
         }
      }
      if( ok ) printf("YES\n");
      else printf("NO\n");
   }
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1123 Is It a Complete AVL Tree(30 分)

An AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. Figures 1-4 illustrate the rotation rules.

F1.jpgF2.jpg
F3.jpgF4.jpg

Now given a sequence of insertions, you are supposed to output the level-order traversal sequence of the resulting AVL tree, and to tell if it is a complete binary tree.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (≤ 20). Then N distinct integer keys are given in the next line. All the numbers in a line are separated by a space.

Output Specification:

For each test case, insert the keys one by one into an initially empty AVL tree. Then first print in a line the level-order traversal sequence of the resulting AVL tree. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line. Then in the next line, print YES if the tree is complete, or NO if not.

Sample Input 1:

5
88 70 61 63 65

Sample Output 1:

70 63 88 61 65
YES

Sample Input 2:

8
88 70 61 96 120 90 65 68

Sample Output 2:

88 65 96 61 70 90 120 68
NO

 

 

#include<bits/stdc++.h>
using namespace std;

typedef struct node{
   int key;
   struct node *Left, *Right;
} *Tree;

Tree L(Tree T){
    Tree temp = T->Right;
    T->Right = temp->Left;
    temp->Left = T;
    return temp;
}

Tree R(Tree T){
    Tree temp = T->Left;
    T->Left = temp->Right;
    temp->Right = T;
    return temp;
}

int getHeight(Tree T){
   if( T == NULL) return 0;
   else return max( getHeight(T->Left) , getHeight(T->Right) ) + 1;
}

void balance( Tree &T, int x){
   int lheight = getHeight( T->Left ), rheight = getHeight( T->Right);
   if( lheight - rheight >= 2 ){
       if(T->Left->key < x) T->Left = L(T->Left);
       T = R(T);
   }
   else if( rheight - lheight >= 2 ){
       if(T->Right->key > x) T->Right = R(T->Right);
       T = L(T);
   }
}

Tree build(Tree T, int x){
   if( T == NULL ){
      Tree u = (Tree) malloc( sizeof(struct node) );
      u->key = x;
      u->Left = u->Right = NULL;
      return u;
   }
   if( x < T->key )  T->Left = build(T->Left, x);
   else T->Right = build(T->Right, x);
   balance( T, x);
   return T;
}

bool levelorder(Tree T){
   bool ok = true;
   int flag = 0;
   vector< int > v;
   queue< Tree > Q;
   Q.push( T );
   while( !Q.empty() ){
      Tree u = Q.front();
      v.push_back(u->key);
      Q.pop();
      if( u->Left && u ->Right ){
         Q.push(u->Left); Q.push(u->Right);
         if( flag ) ok = false;
      }
      else if( u->Left ) { Q.push(u->Left);  if( flag ) ok = false; flag = 1;}
      else if( u->Right) { Q.push(u->Right); ok = false;}
      else flag = 1;
   }
   for(int i = 0; i < (int)v.size(); i++)
      printf("%d%c", v[i], (i == (int)v.size()-1) ? '\n' : ' ');
   return ok;
}

int main(){
   int N;
   cin >> N;
   Tree T = NULL;
   for(int i = 0; i < N; i++){
     int x;
     scanf("%d", &x);
     T  = build(T, x);
   }
   if( levelorder(T) ) cout << "YES\n";
   else cout << "NO\n";
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1124 Raffle for Weibo Followers(20 分)

John got a full mark on PAT. He was so happy that he decided to hold a raffle(抽奖) for his followers on Weibo -- that is, he would select winners from every N followers who forwarded his post, and give away gifts. Now you are supposed to help him generate the list of winners.

Input Specification:

Each input file contains one test case. For each case, the first line gives three positive integers M (≤ 1000), N and S, being the total number of forwards, the skip number of winners, and the index of the first winner (the indices start from 1). Then M lines follow, each gives the nickname (a nonempty string of no more than 20 characters, with no white space or return) of a follower who has forwarded John's post.

Note: it is possible that someone would forward more than once, but no one can win more than once. Hence if the current candidate of a winner has won before, we must skip him/her and consider the next one.

Output Specification:

For each case, print the list of winners in the same order as in the input, each nickname occupies a line. If there is no winner yet, print Keep going... instead.

Sample Input 1:

9 3 2
Imgonnawin!
PickMe
PickMeMeMeee
LookHere
Imgonnawin!
TryAgainAgain
TryAgainAgain
Imgonnawin!
TryAgainAgain

Sample Output 1:

PickMe
Imgonnawin!
TryAgainAgain

Sample Input 2:

2 3 5
Imgonnawin!
PickMe

Sample Output 2:

Keep going...

 

#include<bits/stdc++.h>
using namespace std;

set< string > Myset;

int main(){
   int N, M, P, cnt = 0;
   cin >> N >> M >> P;
   for(int i = 1; i <= N; i++){
       string s;
       cin >> s;
       if( ++cnt >= P && cnt % M == P % M ){
          if( Myset.count(s) )  cnt--;
          else {
            cout << s << endl;
            Myset.insert(s);
          }
       }
   }
   if( Myset.empty() ) cout << "Keep going...\n";
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1125 Chain the Ropes(25 分)

Given some segments of rope, you are supposed to chain them into one rope. Each time you may only fold two segments into loops and chain them into one piece, as shown by the figure. The resulting chain will be treated as another segment of rope and can be folded again. After each chaining, the lengths of the original two segments will be halved.

rope.jpg

Your job is to make the longest possible rope out of N given segments.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (2≤N≤10​4​​). Then N positive integer lengths of the segments are given in the next line, separated by spaces. All the integers are no more than 10​4​​.

Output Specification:

For each case, print in a line the length of the longest possible rope that can be made by the given segments. The result must be rounded to the nearest integer that is no greater than the maximum length.

Sample Input:

8
10 15 12 3 4 13 1 15

Sample Output:

14

 

 

#include<bits/stdc++.h>
using namespace std;


int main(){
   int N;
   cin >> N;
   vector< int > v(N);
   for(int i = 0; i < N; i++)
      scanf("%d", &v[i]);
   sort( v.begin(), v.end() );
   double sum = v[0];
   for(int i = 1; i < N; i++)
      sum = (sum + v[i]) / 2;
   printf("%d\n", (int)floor(sum) );
   return 0;
}

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1126 Eulerian Path(25 分)

In graph theory, an Eulerian path is a path in a graph which visits every edge exactly once. Similarly, an Eulerian circuit is an Eulerian path which starts and ends on the same vertex. They were first discussed by Leonhard Euler while solving the famous Seven Bridges of Konigsberg problem in 1736. It has been proven that connected graphs with all vertices of even degree have an Eulerian circuit, and such graphs are called Eulerian. If there are exactly two vertices of odd degree, all Eulerian paths start at one of them and end at the other. A graph that has an Eulerian path but not an Eulerian circuit is called semi-Eulerian. (Cited from https://en.wikipedia.org/wiki/Eulerian_path)

Given an undirected graph, you are supposed to tell if it is Eulerian, semi-Eulerian, or non-Eulerian.

Input Specification:

Each input file contains one test case. Each case starts with a line containing 2 numbers N (≤ 500), and M, which are the total number of vertices, and the number of edges, respectively. Then M lines follow, each describes an edge by giving the two ends of the edge (the vertices are numbered from 1 to N).

Output Specification:

For each test case, first print in a line the degrees of the vertices in ascending order of their indices. Then in the next line print your conclusion about the graph -- either Eulerian, Semi-Eulerian, or Non-Eulerian. Note that all the numbers in the first line must be separated by exactly 1 space, and there must be no extra space at the beginning or the end of the line.

Sample Input 1:

7 12
5 7
1 2
1 3
2 3
2 4
3 4
5 2
7 6
6 3
4 5
6 4
5 6

Sample Output 1:

2 4 4 4 4 4 2
Eulerian

Sample Input 2:

6 10
1 2
1 3
2 3
2 4
3 4
5 2
6 3
4 5
6 4
5 6

Sample Output 2:

2 4 4 4 3 3
Semi-Eulerian

Sample Input 3:

5 8
1 2
2 5
5 4
4 1
1 3
3 2
3 4
5 3

Sample Output 3:

3 3 4 3 3
Non-Eulerian

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 500+5;
int N, M;

vector< int > degree;
bool d[MAXN][MAXN];
bool v[MAXN];

void dfs(int i){
   v[i] = true;
   for(int j = 0; j < N; j++) if( !v[j] && d[i][j])
      dfs(j);
}

int main(){
   cin >> N >> M;
   degree.resize(N);
   for(int i = 0; i < M; i++){
      int x, y;
      scanf("%d%d", &x, &y);
      degree[--x]++; degree[--y]++;
      d[x][y] = d[y][x] = true;
   }

   bool ok = false;;
   for(int i = 0; i < N; i++) if( !v[i] ){
      if( !ok ) ok = true;
      else { ok = false; break; }
      dfs(i);
   }
   
   int cnt = 0;
   for(int i = 0; i < N; i++){
      printf("%d%c", degree[i], (i == N-1) ? '\n' : ' ');
      if( degree[i] % 2 ) cnt++;
   }
   if( !cnt && ok) printf("Eulerian\n");
   else if( cnt == 2 && ok) printf("Semi-Eulerian\n");
   else printf("Non-Eulerian\n");
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1127 ZigZagging on a Tree(30 分)

Suppose that all the keys in a binary tree are distinct positive integers. A unique binary tree can be determined by a given pair of postorder and inorder traversal sequences. And it is a simple standard routine to print the numbers in level-order. However, if you think the problem is too simple, then you are too naive. This time you are supposed to print the numbers in "zigzagging order" -- that is, starting from the root, print the numbers level-by-level, alternating between left to right and right to left. For example, for the following tree you must output: 1 11 5 8 17 12 20 15.

zigzag.jpg

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary tree. The second line gives the inorder sequence and the third line gives the postorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print the zigzagging sequence of the tree in a line. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:

8
12 11 20 17 1 15 8 5
12 20 17 11 15 8 5 1

Sample Output:

1 11 5 8 17 12 20 15

 

#include<bits/stdc++.h>
using namespace std;

int N;
vector< int > in, post;
vector< vector<int> > v;

void zigzagging(int inl, int inr, int postr, int deep){
   if(inl > inr) return;
   int i = inl;
   while( in[i] != post[postr] ) i++;
   v[deep].push_back( in[i] );
   zigzagging(inl, i-1, i+postr-inr-1, deep+1);
   zigzagging(i+1, inr, postr-1, deep+1);
}

int main(){
   cin >> N;
   in.resize(N);
   post.resize(N);
   v.resize(N);
   for(int i = 0; i < N; i++) scanf("%d", &in[i]);
   for(int i = 0; i < N; i++) scanf("%d", &post[i]);
   zigzagging(0, N-1, N-1, 0);
   int k = 0;
   vector< int > ans;
   for(auto &V : v){
      if(k) for(int i = 0; i < (int)V.size(); i++)
         ans.push_back( V[i] );
      else  for(int i = (int)V.size()-1; i >= 0 ; i--)
        ans.push_back( V[i] );
      k ^= 1;
   }
   for(int i = 0; i < (int)ans.size(); i++)
       printf("%d%c", ans[i], (i == (int)ans.size()-1) ? '\n' : ' ' );
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1128 N Queens Puzzle(20 分)

The "eight queens puzzle" is the problem of placing eight chess queens on an 8×88\times 88×8 chessboard so that no two queens threaten each other. Thus, a solution requires that no two queens share the same row, column, or diagonal. The eight queens puzzle is an example of the more general NNN queens problem of placing NNN non-attacking queens on an N×NN\times NN×N chessboard. (From Wikipedia - "Eight queens puzzle".)

Here you are NOT asked to solve the puzzles. Instead, you are supposed to judge whether or not a given configuration of the chessboard is a solution. To simplify the representation of a chessboard, let us assume that no two queens will be placed in the same column. Then a configuration can be represented by a simple integer sequence (Q1,Q2,⋯,QN)(Q_1, Q_2, \cdots , Q_N)(Q​1​​,Q​2​​,⋯,Q​N​​), where QiQ_iQ​i​​ is the row number of the queen in the iii-th column. For example, Figure 1 can be represented by (4, 6, 8, 2, 7, 1, 3, 5) and it is indeed a solution to the 8 queens puzzle; while Figure 2 can be represented by (4, 6, 7, 2, 8, 1, 9, 5, 3) and is NOT a 9 queens' solution.

8q.jpg 9q.jpg
Figure 1 Figure 2

Input Specification:

Each input file contains several test cases. The first line gives an integer KKK (1<K≤2001<K\le 2001<K≤200). Then KKK lines follow, each gives a configuration in the format "NNN Q1Q_1Q​1​​ Q2Q_2Q​2​​ ... QNQ_NQ​N​​", where 4≤N≤10004\le N\le 10004≤N≤1000 and it is guaranteed that 1≤Qi≤N1\le Q_i\le N1≤Q​i​​≤N for all i=1,⋯,Ni=1, \cdots , Ni=1,⋯,N. The numbers are separated by spaces.

Output Specification:

For each configuration, if it is a solution to the NNN queens problem, print YES in a line; or NO if not.

Sample Input:

4
8 4 6 8 2 7 1 3 5
9 4 6 7 2 8 1 9 5 3
6 1 5 2 6 4 3
5 1 3 5 2 4

Sample Output:

YES
NO
NO
YES

 

#include<bits/stdc++.h>
using namespace std;

int main(){
   int N, M, x;
   cin >> N;
   while( N-- ){
      bool ok = true;
      cin >> M;
      vector< bool > v(M+1, false), v1(2*M+1, false), v2(2*M+1, false);
      for(int i = 0; i < M; i++){
         scanf("%d", &x);
         if( !ok ) continue;
         if(  v[x] || v1[x+M-i] || v2[x+i] ) ok = false;
         else  v[x] = v1[x+M-i] = v2[x+i] = true;
      }
      printf("%s\n", ok ? "YES" : "NO" );
   }
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1129 Recommendation System(25 分)

Recommendation system predicts the preference that a user would give to an item. Now you are asked to program a very simple recommendation system that rates the user's preference by the number of times that an item has been accessed by this user.

Input Specification:

Each input file contains one test case. For each test case, the first line contains two positive integers: N (≤ 50,000), the total number of queries, and K (≤ 10), the maximum number of recommendations the system must show to the user. Then given in the second line are the indices of items that the user is accessing -- for the sake of simplicity, all the items are indexed from 1 to N. All the numbers in a line are separated by a space.

Output Specification:

For each case, process the queries one by one. Output the recommendations for each query in a line in the format:

query: rec[1] rec[2] ... rec[K]

where query is the item that the user is accessing, and rec[i] (i=1, ... K) is the i-th item that the system recommends to the user. The first K items that have been accessed most frequently are supposed to be recommended in non-increasing order of their frequencies. If there is a tie, the items will be ordered by their indices in increasing order.

Note: there is no output for the first item since it is impossible to give any recommendation at the time. It is guaranteed to have the output for at least one query.

Sample Input:

12 3
3 5 7 5 5 3 2 1 8 3 8 12

Sample Output:

5: 3
7: 3 5
5: 3 5 7
5: 5 3 7
3: 5 3 7
2: 5 3 7
1: 5 3 2
8: 5 3 1
3: 5 3 1
8: 3 5 1
12: 3 5 8
#include<bits/stdc++.h>
using namespace std;

const int MAXN = 5e4+10;

struct node{
   int id, Time;
   bool operator < (const node &rhs) const {
      return Time == rhs.Time ?  id < rhs.id  : Time > rhs.Time;
   }
};

set< node > Myset;
int book[MAXN];

int main(){
   int N, M, x;
   cin >> N >> M >> x;
   Myset.insert( {x, 1} );
   book[x]++;
   for(int i = 1; i < N; i++){
      scanf("%d", &x);
      printf("%d:", x);
      int j = 0;
      for(auto it = Myset.begin(); j < M && it != Myset.end(); j++, it++)
         printf(" %d", it->id);
      putchar('\n');
      auto it = Myset.find( {x, book[x]} );
      if(it == Myset.end() )  Myset.insert( {x, 1} );
      else {
         Myset.erase(it);
         Myset.insert( {x, book[x]+1} );
      }
      book[x]++;
   }
   return 0;
}

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1130 Infix Expression(25 分)

Given a syntax tree (binary), you are supposed to output the corresponding infix expression, with parentheses reflecting the precedences of the operators.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤ 20) which is the total number of nodes in the syntax tree. Then N lines follow, each gives the information of a node (the i-th line corresponds to the i-th node) in the format:

data left_child right_child

where data is a string of no more than 10 characters, left_child and right_child are the indices of this node's left and right children, respectively. The nodes are indexed from 1 to N. The NULL link is represented by −1. The figures 1 and 2 correspond to the samples 1 and 2, respectively.

infix1.JPGinfix2.JPG
Figure 1Figure 2

Output Specification:

For each case, print in a line the infix expression, with parentheses reflecting the precedences of the operators. Note that there must be no extra parentheses for the final expression, as is shown by the samples. There must be no space between any symbols.

Sample Input 1:

8
* 8 7
a -1 -1
* 4 1
+ 2 5
b -1 -1
d -1 -1
- -1 6
c -1 -1

Sample Output 1:

(a+b)*(c*(-d))

Sample Input 2:

8
2.35 -1 -1
* 6 1
- -1 4
% 7 8
+ 2 3
a -1 -1
str -1 -1
871 -1 -1

Sample Output 2:

(a*2.35)+(-(str%871))
#include<bits/stdc++.h>
using namespace std;

const int MAXN = 5e4+10;
int N, T = 0;
vector< string > expr;
vector< vector< int > > v;

void dfs( int i ){
   if(i != T && ( v[i][0] != -1 || v[i][1] != -1 ) ) putchar('(');
   if( v[i][0] != -1 ) dfs( v[i][0] );
   cout << expr[i];
   if( v[i][1] != -1 ) dfs( v[i][1] );
   if(i != T && ( v[i][0] != -1 || v[i][1] != -1 ) ) putchar(')');
}

int main(){
   cin >> N;
   vector< int > head(N);
   v.resize(N);
   expr.resize(N);
   for(int i = 0; i < N; i++){
      string a; int x, y;
      cin >> a >> x >> y;
      if( x != -1 ) head[--x]++;
      if( y != -1 ) head[--y]++;
      v[i].push_back(x);
      v[i].push_back(y);
      expr[i] = a;
   }

   while( head[T] ) T++;
   dfs(T);
   return 0;
}

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1131 Subway Map(30 分)

In the big cities, the subway systems always look so complex to the visitors. To give you some sense, the following figure shows the map of Beijing subway. Now you are supposed to help people with your computer skills! Given the starting position of your user, your task is to find the quickest way to his/her destination.

subwaymap.jpg

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (≤ 100), the number of subway lines. Then N lines follow, with the i-th (i=1,⋯,N) line describes the i-th subway line in the format:

M S[1] S[2] ... S[M]

where M (≤ 100) is the number of stops, and S[i]'s (i=1,⋯,M) are the indices of the stations (the indices are 4-digit numbers from 0000 to 9999) along the line. It is guaranteed that the stations are given in the correct order -- that is, the train travels between S[i] and S[i+1] (i=1,⋯,M−1) without any stop.

Note: It is possible to have loops, but not self-loop (no train starts from S and stops at S without passing through another station). Each station interval belongs to a unique subway line. Although the lines may cross each other at some stations (so called "transfer stations"), no station can be the conjunction of more than 5 lines.

After the description of the subway, another positive integer K (≤ 10) is given. Then K lines follow, each gives a query from your user: the two indices as the starting station and the destination, respectively.

The following figure shows the sample map.

samplemap.jpg

Note: It is guaranteed that all the stations are reachable, and all the queries consist of legal station numbers.

Output Specification:

For each query, first print in a line the minimum number of stops. Then you are supposed to show the optimal path in a friendly format as the following:

Take Line#X1 from S1 to S2.
Take Line#X2 from S2 to S3.
......

where Xi's are the line numbers and Si's are the station indices. Note: Besides the starting and ending stations, only the transfer stations shall be printed.

If the quickest path is not unique, output the one with the minimum number of transfers, which is guaranteed to be unique.

Sample Input:

4
7 1001 3212 1003 1204 1005 1306 7797
9 9988 2333 1204 2006 2005 2004 2003 2302 2001
13 3011 3812 3013 3001 1306 3003 2333 3066 3212 3008 2302 3010 3011
4 6666 8432 4011 1306
3
3011 3013
6666 2001
2004 3001

Sample Output:

2
Take Line#3 from 3011 to 3013.
10
Take Line#4 from 6666 to 1306.
Take Line#3 from 1306 to 2302.
Take Line#2 from 2302 to 2001.
6
Take Line#2 from 2004 to 1204.
Take Line#1 from 1204 to 1306.
Take Line#3 from 1306 to 3001.

 

 

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 1e4+10, INF = 9999999;

int M, Q, S, D, n = 0;
int d[MAXN][MAXN];
int dist[MAXN], path[MAXN], road[MAXN], line[MAXN];
bool v[MAXN];

map<int, int> IDcache, CityCache;

int getid(int city){
   if( !IDcache.count(city) ){
      IDcache[city] = n;
      CityCache[n++] = city;
   }
   return IDcache[city];
}

void print(){
   printf("%d\n", dist[D]);
   vector< int > ans;
   int preline = -1;
   for(int i = D; i != S; i = path[i]) if(line[i] != preline ){
      ans.push_back( i );
      preline = line[i];
   }
   ans.push_back( S );
   for(int i = ans.size()-1; i > 0; i--)
      printf("Take Line#%d from %04d to %04d.\n", line[ ans[i-1] ] , CityCache[ ans[i] ], CityCache[ ans[i-1] ] );
}

void Dijkstra(){
   fill(dist, dist+MAXN, INF);
   memset(v, false, sizeof(v) );
   memset(road, 0, sizeof(road));
   memset(line, 0, sizeof(line));
   dist[S] = 0;
   for(int i = 0; i < n; i++){
      int x = -1, minn = INF;
      for(int y = 0; y < n; y++) if( !v[y] && dist[y] < minn){
         minn = dist[ x = y];
      }
      if( x < 0 ) break;
      v[x] = true;
      for(int y = 0; y < n; y++) if( !v[y] && d[x][y]){
         if(dist[y] > dist[x] + 1){
            dist[y] = dist[x] + 1;
            road[y] = (d[x][y] == line[x]) ? road[x] : road[x]+1;
            line[y] = d[x][y];
            path[y] = x;
         }
         else if(dist[y] == dist[x] + 1 && road[y] > ( (d[x][y] == line[x]) ? road[x] : road[x]+1) ){
            road[y] = d[x][y] == line[x] ? road[x] : road[x] + 1;
            line[y] = d[x][y];
            path[y] = x;
         }
      }
   }
   print();
}

int main(){
   cin >> M;
   for(int i = 1; i <= M; i++){
      int N, id, x, y;
      scanf("%d%d", &N, &id);
      x = getid( id );
      while( --N ){
         scanf("%d", &id);
         y = getid( id );
         d[x][y] = d[y][x] = i;
         x = y;
      }
   }
   cin >> Q;
   while( Q-- ){
      scanf("%d%d", &S, &D);
      S = getid(S);
      D = getid(D);
      Dijkstra();
   }
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1132 Cut Integer(20 分)

Cutting an integer means to cut a K digits lone integer Z into two integers of (K/2) digits long integers A and B. For example, after cutting Z = 167334, we have A = 167 and B = 334. It is interesting to see that Z can be devided by the product of A and B, as 167334 / (167 × 334) = 3. Given an integer Z, you are supposed to test if it is such an integer.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤ 20). Then N lines follow, each gives an integer Z (10 ≤ Z <2​31​​). It is guaranteed that the number of digits of Z is an even number.

Output Specification:

For each case, print a single line Yes if it is such a number, or No if not.

Sample Input:

3
167334
2333
12345678

Sample Output:

Yes
No
No

 

#include<bits/stdc++.h>
using namespace std;

int main(){
   int T;
   cin >> T;
   while( T-- ){
      string s;
      long long a, b, c;
      cin >> s;
      a = stoi(s);
      b = stoi( s.substr(0, s.length()/2 ) );
      c = stoi( s.substr( s.length()/2 ) );
      if( b*c != 0 && a % (b*c) == 0) cout << "Yes\n";
      else cout << "No\n";
   }
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1133 Splitting A Linked List(25 分)

Given a singly linked list, you are supposed to rearrange its elements so that all the negative values appear before all of the non-negatives, and all the values in [0, K] appear before all those greater than K. The order of the elements inside each class must not be changed. For example, given the list being 18→7→-4→0→5→-6→10→11→-2 and K being 10, you must output -4→-6→-2→7→0→5→10→18→11.

Input Specification:

Each input file contains one test case. For each case, the first line contains the address of the first node, a positive N (≤10​5​​) which is the total number of nodes, and a positive K (≤10​3​​). The address of a node is a 5-digit nonnegative integer, and NULL is represented by −1.

Then N lines follow, each describes a node in the format:

Address Data Next

where Address is the position of the node, Data is an integer in [−10​5​​,10​5​​], and Next is the position of the next node. It is guaranteed that the list is not empty.

Output Specification:

For each case, output in order (from beginning to the end of the list) the resulting linked list. Each node occupies a line, and is printed in the same format as in the input.

Sample Input:

00100 9 10
23333 10 27777
00000 0 99999
00100 18 12309
68237 -6 23333
33218 -4 00000
48652 -2 -1
99999 5 68237
27777 11 48652
12309 7 33218

Sample Output:

33218 -4 68237
68237 -6 48652
48652 -2 12309
12309 7 00000
00000 0 99999
99999 5 23333
23333 10 00100
00100 18 27777
27777 11 -1

 

#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1e5+10;
struct node{
  int Address, Data, Next;
}a[MAXN];

int T, N, K;
vector< node > v[3], ans;

int main(){
   cin >> T >> N >> K;
   for(int i = 0; i < N; i++){
      node temp;
      scanf("%d%d%d", &temp.Address, &temp.Data, &temp.Next);
      a[ temp.Address ] = temp;
   }  
   int p = T;
   while( p != -1 ){
      if( a[p].Data < 0) v[0].push_back( a[p] );
      else if( a[p].Data <= K) v[1].push_back( a[p] );
      else v[2].push_back( a[p] );
      p = a[p].Next;
   }
   for(int i = 0; i < 3; i++)
      for(auto &j : v[i])
         ans.push_back(j);
   N = ans.size();
   for(int i = 0; i < N; i++){
      if(i != N-1) printf("%05d %d %05d\n", ans[i].Address, ans[i].Data, ans[i+1].Address);
      else printf("%05d %d -1\n", ans[i].Address, ans[i].Data);
   }
   return 0;
}

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------------------------------------

1134 Vertex Cover(25 分)

A vertex cover of a graph is a set of vertices such that each edge of the graph is incident to at least one vertex of the set. Now given a graph with several vertex sets, you are supposed to tell if each of them is a vertex cover or not.

Input Specification:

Each input file contains one test case. For each case, the first line gives two positive integers N and M (both no more than 10​4​​), being the total numbers of vertices and the edges, respectively. Then M lines follow, each describes an edge by giving the indices (from 0 to N−1) of the two ends of the edge.

After the graph, a positive integer K (≤ 100) is given, which is the number of queries. Then K lines of queries follow, each in the format:

N​v​​ v[1] v[2]⋯v[N​v​​]

where N​v​​ is the number of vertices in the set, and v[i]'s are the indices of the vertices.

Output Specification:

For each query, print in a line Yes if the set is a vertex cover, or No if not.

Sample Input:

10 11
8 7
6 8
4 5
8 4
8 1
1 2
1 4
9 8
9 1
1 0
2 4
5
4 0 3 8 4
6 6 1 7 5 4 9
3 1 8 4
2 2 8
7 9 8 7 6 5 4 2

Sample Output:

No
Yes
Yes
No
No
#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1e5+10;
int N, M, K, Q;
vector< vector< int > > v;

int main(){
   cin >> N >> M;
   v.resize( N );
   for(int i = 0; i < M; i++){
      int x, y;
      scanf("%d%d", &x, &y);
      v[x].push_back(i);
      v[y].push_back(i);
   }
   cin >> Q;
   while( Q-- ){
      cin >> K;
      vector< bool > hash(M);
      int cnt = 0;
      bool ok = false;
      for(int i = 0; i < K; i++){
         int x;
         scanf("%d", &x);
         if( ok ) continue;
         for(auto &i : v[x]) if( !hash[i] ){
            hash[i] = true;
            if( ++cnt == M) ok = true;
         }
      }
      if(ok) cout << "Yes\n";
      else cout << "No\n";
   }
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1135 Is It A Red-Black Tree(30 分)

There is a kind of balanced binary search tree named red-black tree in the data structure. It has the following 5 properties:

  • (1) Every node is either red or black.
  • (2) The root is black.
  • (3) Every leaf (NULL) is black.
  • (4) If a node is red, then both its children are black.
  • (5) For each node, all simple paths from the node to descendant leaves contain the same number of black nodes.

For example, the tree in Figure 1 is a red-black tree, while the ones in Figure 2 and 3 are not.

rbf1.jpgrbf2.jpgrbf3.jpg
Figure 1Figure 2Figure 3

For each given binary search tree, you are supposed to tell if it is a legal red-black tree.

Input Specification:

Each input file contains several test cases. The first line gives a positive integer K (≤30) which is the total number of cases. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary tree. The second line gives the preorder traversal sequence of the tree. While all the keys in a tree are positive integers, we use negative signs to represent red nodes. All the numbers in a line are separated by a space. The sample input cases correspond to the trees shown in Figure 1, 2 and 3.

Output Specification:

For each test case, print in a line "Yes" if the given tree is a red-black tree, or "No" if not.

Sample Input:

3
9
7 -2 1 5 -4 -11 8 14 -15
9
11 -2 1 -7 5 -4 8 14 -15
8
10 -7 5 -6 8 15 -11 17

Sample Output:

Yes
No
No
#include<bits/stdc++.h>
using namespace std;

int M, N, x;

typedef struct node{
   int v;
   struct node *L, *R;
} *Tree;

Tree build(Tree T, int x){
   if(T == NULL){
      T = new struct node();
      T->L = T->R = NULL;
      T->v = x;
   }
   else if( abs(T->v) > abs(x) ) T->L = build(T->L, x);
   else  T->R = build(T->R, x);
   return T;
}


int CNT = -1;

bool Check( Tree T, int flag, int cnt){	
   if( T == NULL ){
       if( CNT == -1 ) CNT = cnt;
       if( cnt != CNT ) return false;
       else return true;
   }
   cnt += ( T->v > 0 ? 1 : 0 );
   if( flag )
      return Check(T->L, T->v>0?1:0, cnt ) && Check(T->R, T->v>0?1:0, cnt );
   else{
      if( T->v < 0) return false;;
      return Check(T->L, 1, cnt) && Check(T->R, 1, cnt);
   }
}

int main(){
   cin >> M;
   while( M-- ){
      cin >> N;
      Tree T = NULL;
      for(int i = 0; i < N; i++){
          scanf("%d", &x);
          T = build(T, x);
      }
      CNT = -1;
      if( T->v > 0 && Check(T, 1, 0) ) cout << "Yes\n";
      else cout << "No\n";
   }
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1136 A Delayed Palindrome(20 分)

Consider a positive integer N written in standard notation with k+1 digits a​i​​ as a​k​​⋯a​1​​a​0​​ with 0≤a​i​​<10 for all i and a​k​​>0. Then N is palindromic if and only if a​i​​=a​k−i​​ for all i. Zero is written 0 and is also palindromic by definition.

Non-palindromic numbers can be paired with palindromic ones via a series of operations. First, the non-palindromic number is reversed and the result is added to the original number. If the result is not a palindromic number, this is repeated until it gives a palindromic number. Such number is called a delayed palindrome. (Quoted from https://en.wikipedia.org/wiki/Palindromic_number )

Given any positive integer, you are supposed to find its paired palindromic number.

Input Specification:

Each input file contains one test case which gives a positive integer no more than 1000 digits.

Output Specification:

For each test case, print line by line the process of finding the palindromic number. The format of each line is the following:

A + B = C

where A is the original number, B is the reversed A, and C is their sum. A starts being the input number, and this process ends until C becomes a palindromic number -- in this case we print in the last line C is a palindromic number.; or if a palindromic number cannot be found in 10 iterations, print Not found in 10 iterations. instead.

Sample Input 1:

97152

Sample Output 1:

97152 + 25179 = 122331
122331 + 133221 = 255552
255552 is a palindromic number.

Sample Input 2:

196

Sample Output 2:

196 + 691 = 887
887 + 788 = 1675
1675 + 5761 = 7436
7436 + 6347 = 13783
13783 + 38731 = 52514
52514 + 41525 = 94039
94039 + 93049 = 187088
187088 + 880781 = 1067869
1067869 + 9687601 = 10755470
10755470 + 07455701 = 18211171
Not found in 10 iterations.
#include<bits/stdc++.h>
using namespace std;

string add(string a, string b){
  string sum = "";
  int len = a.length(), c=0, cc=0;
  while(len--){
     cc=c;
     sum=char( ((a[len]+b[len]+cc-'0') > '9') ? (c=1, a[len]+b[len]+cc-'0'-10) : (c=0, a[len]+b[len]+cc-'0')) + sum;
  }
  if(c)  sum = '1'+sum;
  return sum;
}


int main(){
   int T = 10;
   string a, b;
   cin >> a;
   while( T-- ){
   	  b = a;
   	  reverse(b.begin(), b.end());
   	  if(a == b) {
   	  	 cout << a << " is a palindromic number.\n";
   	  	 return 0;
   	  }
   	  cout << a << " + " << b << " = ";
   	  a = add(a, b);
   	  cout << a << endl;
   }
   cout << "Not found in 10 iterations.\n";
   return 0;
}

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1137 Final Grading(25 分)

For a student taking the online course "Data Structures" on China University MOOC (http://www.icourse163.org/), to be qualified for a certificate, he/she must first obtain no less than 200 points from the online programming assignments, and then receive a final grade no less than 60 out of 100. The final grade is calculated by G=(Gmid−term×40%+Gfinal×60%)G = (G_{mid-term}\times 40\% + G_{final}\times 60\%)G=(G​mid−term​​×40%+G​final​​×60%) if Gmid−term>GfinalG_{mid-term} > G_{final}G​mid−term​​>G​final​​, or GfinalG_{final}G​final​​ will be taken as the final grade GGG. Here Gmid−termG_{mid-term}G​mid−term​​ and GfinalG_{final}G​final​​ are the student's scores of the mid-term and the final exams, respectively.

The problem is that different exams have different grading sheets. Your job is to write a program to merge all the grading sheets into one.

Input Specification:

Each input file contains one test case. For each case, the first line gives three positive integers: P , the number of students having done the online programming assignments; M, the number of students on the mid-term list; and N, the number of students on the final exam list. All the numbers are no more than 10,000.

Then three blocks follow. The first block contains P online programming scores GpG_pG​p​​'s; the second one contains M mid-term scores Gmid−termG_{mid-term}G​mid−term​​'s; and the last one contains N final exam scores GfinalG_{final}G​final​​'s. Each score occupies a line with the format: StudentID Score, where StudentID is a string of no more than 20 English letters and digits, and Score is a nonnegative integer (the maximum score of the online programming is 900, and that of the mid-term and final exams is 100).

Output Specification:

For each case, print the list of students who are qualified for certificates. Each student occupies a line with the format:

StudentID GpG_pG​p​​ Gmid−termG_{mid-term}G​mid−term​​ GfinalG_{final}G​final​​ GGG

If some score does not exist, output "−1-1−1" instead. The output must be sorted in descending order of their final grades (GGG must be rounded up to an integer). If there is a tie, output in ascending order of their StudentID's. It is guaranteed that the StudentID's are all distinct, and there is at least one qullified student.

Sample Input:

6 6 7
01234 880
a1903 199
ydjh2 200
wehu8 300
dx86w 220
missing 400
ydhfu77 99
wehu8 55
ydjh2 98
dx86w 88
a1903 86
01234 39
ydhfu77 88
a1903 66
01234 58
wehu8 84
ydjh2 82
missing 99
dx86w 81

Sample Output:

missing 400 -1 99 99
ydjh2 200 98 82 88
dx86w 220 88 81 84
wehu8 300 55 84 84
#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1e4 + 5;
int M, N, P;
map<string, int > IDcache;

struct node{
	string Name;
	int point, mid, final, G;
	bool operator < (const node &rhs) const{
	   if(G != rhs.G) return G > rhs.G;
	   else return Name < rhs.Name;
	}
}stu[MAXN];

int main(){
   cin >> M >> N >> P;
   string Name;
   int Point, cnt = 0;
   while( M-- ){
   	  cin >> Name >> Point;
      if( Point < 200) continue;
      IDcache[Name] = cnt;
	    stu[cnt++] = {Name, Point, -1, -1, -1};
   }
   while( N-- ){
   	  cin >> Name >> Point;
   	  if( IDcache.find(Name) == IDcache.end() ) continue;
   	  stu[IDcache[Name]  ].mid = Point;
   }   
   
   vector< node > Ans;
   while( P-- ){
   	  cin >> Name >> Point;
   	  if( IDcache.find(Name) == IDcache.end() ) continue;
   	  node &t = stu[ IDcache[Name] ];
   	  t.final = Point;
   	  if(t.final > t.mid) t.G = t.final;
   	  else t.G = t.mid*0.4 + t.final*0.6 + 0.5;
   	  if(t.G >= 60) Ans.push_back(t);
   }
   sort(Ans.begin(), Ans.end());
   
   for(int i = 0; i < Ans.size(); i++)
   	  cout << Ans[i].Name << " " << Ans[i].point << " " << Ans[i].mid << " " << Ans[i].final << " " << Ans[i].G << endl;
   
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1138 Postorder Traversal(25 分)

Suppose that all the keys in a binary tree are distinct positive integers. Given the preorder and inorder traversal sequences, you are supposed to output the first number of the postorder traversal sequence of the corresponding binary tree.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤ 50,000), the total number of nodes in the binary tree. The second line gives the preorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the first number of the postorder traversal sequence of the corresponding binary tree.

Sample Input:

7
1 2 3 4 5 6 7
2 3 1 5 4 7 6

Sample Output:

3

 

#include <bits/stdc++.h>
using namespace std;
vector< int > pre, in ,post;
int k;

void postOrder(int prel, int inl, int inr) {
    if (inl > inr ) return;
    int i = inl;
    while (in[i] != pre[prel]) i++;
    post[--k] = in[i];
    postOrder(prel+i-inl+1, i+1, inr);
    postOrder(prel+1, inl, i-1);
}

int main() {
    int n;
    scanf("%d", &n);
    pre.resize(n);
    in.resize(n);
    post.resize( k = n );
    for (int i = 0; i < n; i++) scanf("%d", &pre[i]);
    for (int i = 0; i < n; i++) scanf("%d", &in[i]);
    postOrder(0, 0, n-1);
    cout<<post[0];
    return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1139 First Contact(30 分)

Unlike in nowadays, the way that boys and girls expressing their feelings of love was quite subtle in the early years. When a boy A had a crush on a girl B, he would usually not contact her directly in the first place. Instead, he might ask another boy C, one of his close friends, to ask another girl D, who was a friend of both B and C, to send a message to B -- quite a long shot, isn't it? Girls would do analogously.

Here given a network of friendship relations, you are supposed to help a boy or a girl to list all their friends who can possibly help them making the first contact.

Input Specification:

Each input file contains one test case. For each case, the first line gives two positive integers N (1 < N ≤ 300) and M, being the total number of people and the number of friendship relations, respectively. Then M lines follow, each gives a pair of friends. Here a person is represented by a 4-digit ID. To tell their genders, we use a negative sign to represent girls.

After the relations, a positive integer K (≤ 100) is given, which is the number of queries. Then K lines of queries follow, each gives a pair of lovers, separated by a space. It is assumed that the first one is having a crush on the second one.

Output Specification:

For each query, first print in a line the number of different pairs of friends they can find to help them, then in each line print the IDs of a pair of friends.

If the lovers A and B are of opposite genders, you must first print the friend of A who is of the same gender of A, then the friend of B, who is of the same gender of B. If they are of the same gender, then both friends must be in the same gender as theirs. It is guaranteed that each person has only one gender.

The friends must be printed in non-decreasing order of the first IDs, and for the same first ones, in increasing order of the seconds ones.

Sample Input:

10 18
-2001 1001
-2002 -2001
1004 1001
-2004 -2001
-2003 1005
1005 -2001
1001 -2003
1002 1001
1002 -2004
-2004 1001
1003 -2002
-2003 1003
1004 -2002
-2001 -2003
1001 1003
1003 -2001
1002 -2001
-2002 -2003
5
1001 -2001
-2003 1001
1005 -2001
-2002 -2004
1111 -2003

Sample Output:

4
1002 2004
1003 2002
1003 2003
1004 2002
4
2001 1002
2001 1003
2002 1003
2002 1004
0
1
2003 2001
0
#include<bits/stdc++.h>
using namespace std;

const int MAXN = 300+5;
int N, M, n = 0;
unordered_map<int, int> IDCache;
unordered_map<int, int> NameCache;
int d[MAXN][MAXN];
char s1[10], s2[10];

int getid( char *s ){
  int x = abs( atoi(s) ), X = x;
  if( s[0] != '-' )  x += 10000;
	if( !IDCache.count( x ) ){
		IDCache[ x ] = n;
		NameCache[ n++ ] = X;
	}
	return IDCache[ x ];
}

int main(){
   cin >> N >> M;
   while( M-- ){
   	  scanf("%s%s", s1, s2);
      int idx = getid( s1  );
      int idy = getid( s2 );
      d[idx][idy] = d[idy][idx] = strlen(s1) == strlen(s2) ? 1 : -1 ;
   }
   cin >> N;
   while( N-- ){
   	  scanf("%s%s", s1, s2);
      int idx = getid( s1  );
      int idy = getid( s2 );
   	  vector< pair<int, int> > v;
   	  int flag = strlen(s1) == strlen(s2) ? 1 : -1 ;
   	  for(int i = 0; i < n; i++) if( i != idy && d[idx][i] == 1 )
   	  	 for(int j = 0; j < n; j++) if(j != idx && d[i][j] == flag && d[j][idy] == 1)
   	  	 	 v.push_back( make_pair( NameCache[i], NameCache[j] ) );
   	  sort(v.begin(), v.end());
   	  cout << v.size() << endl;
	    for(int i = 0; i < v.size(); i++)
	  	   printf("%04d %04d\n", v[i].first, v[i].second);	   
   }
   return 0;
}

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1140 Look-and-say Sequence(20 分)

Look-and-say sequence is a sequence of integers as the following:

D, D1, D111, D113, D11231, D112213111, ...

where D is in [0, 9] except 1. The (n+1)st number is a kind of description of the nth number. For example, the 2nd number means that there is one D in the 1st number, and hence it is D1; the 2nd number consists of one D (corresponding to D1) and one 1 (corresponding to 11), therefore the 3rd number is D111; or since the 4th number is D113, it consists of one D, two 1's, and one 3, so the next number must be D11231. This definition works for D = 1 as well. Now you are supposed to calculate the Nth number in a look-and-say sequence of a given digit D.

Input Specification:

Each input file contains one test case, which gives D (in [0, 9]) and a positive integer N (≤ 40), separated by a space.

Output Specification:

Print in a line the Nth number in a look-and-say sequence of D.

Sample Input:

1 8

Sample Output:

1123123111
#include<bits/stdc++.h>
using namespace std;

int main(){
   string a;
   int N;
   cin >> a >> N;
   while( --N ){
      string b;
      int len = a.length();
      for(int i = 0; i < len;){
         int j = i+1;
         while(j < len && a[j] == a[i]) j++;
         b += a[i] + to_string(j-i);
         i = j;
      }
      a = b;
   }
   cout << a;
   return 0;
}

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1141 PAT Ranking of Institutions(25 分)

After each PAT, the PAT Center will announce the ranking of institutions based on their students' performances. Now you are asked to generate the ranklist.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤10​5​​), which is the number of testees. Then N lines follow, each gives the information of a testee in the following format:

ID Score School

where ID is a string of 6 characters with the first one representing the test level: B stands for the basic level, A the advanced level and T the top level; Score is an integer in [0, 100]; and School is the institution code which is a string of no more than 6 English letters (case insensitive). Note: it is guaranteed that ID is unique for each testee.

Output Specification:

For each case, first print in a line the total number of institutions. Then output the ranklist of institutions in nondecreasing order of their ranks in the following format:

Rank School TWS Ns

where Rank is the rank (start from 1) of the institution; School is the institution code (all in lower case); ; TWS is the total weighted score which is defined to be the integer part of ScoreB/1.5 + ScoreA + ScoreT*1.5, where ScoreX is the total score of the testees belong to this institution on level X; and Ns is the total number of testees who belong to this institution.

The institutions are ranked according to their TWS. If there is a tie, the institutions are supposed to have the same rank, and they shall be printed in ascending order of Ns. If there is still a tie, they shall be printed in alphabetical order of their codes.

Sample Input:

10
A57908 85 Au
B57908 54 LanX
A37487 60 au
T28374 67 CMU
T32486 24 hypu
A66734 92 cmu
B76378 71 AU
A47780 45 lanx
A72809 100 pku
A03274 45 hypu

Sample Output:

5
1 cmu 192 2
1 au 192 3
3 pku 100 1
4 hypu 81 2
#include<bits/stdc++.h>
using namespace std;

const int MAXN = 1e5+10;
unordered_map< string, int > SchoolCache;
int Count = 0;

struct node{
   string school;
   int cnt, pos, mark;
   double Mark;
   bool operator < (const node &rhs) const {
      if( mark != rhs.mark) return mark > rhs.mark;
      if(cnt != rhs.cnt) return cnt < rhs.cnt;
      return school < rhs.school;
   }
}v[MAXN];

int getid(string &school){
   for(auto &i : school)  if( isupper(i) )  i = tolower(i);
   if( !SchoolCache.count( school) ) SchoolCache[ school ] = Count++;
   return SchoolCache[ school ];
}

int main(){
   int N, score;
   cin >> N;
   getchar();
   for(int i = 0; i < N; i++){
      char id[10], s[10];
      scanf("%s%d%s", id, &score, s);
      string school(s);
      node &t = v[ getid( school ) ];
      t.school = school;
      t.cnt++;
      if(id[0] == 'A') t.Mark += score;
      else if(id[0] == 'T') t.Mark += (score*1.5);
      else t.Mark += (score/1.5);
   }
   for(int i = 0; i < Count; i++) v[i].mark = (int)v[i].Mark;
   sort(v, v+Count);
   cout << Count << endl;
   for(int i = 0; i < Count; i++){
      if( i && v[i].mark == v[i-1].mark)   v[i].pos = v[i-1].pos;
      else v[i].pos = i+1;
      printf("%d %s %d %d\n", v[i].pos, v[i].school.c_str(), v[i].mark, v[i].cnt);
   }
   return 0;
}

 

 

---------------------------------------------------------------------------------------------------------------------------

1142 Maximal Clique(25 分)

A clique is a subset of vertices of an undirected graph such that every two distinct vertices in the clique are adjacent. A maximal clique is a clique that cannot be extended by including one more adjacent vertex. (Quoted from https://en.wikipedia.org/wiki/Clique_(graph_theory))

Now it is your job to judge if a given subset of vertices can form a maximal clique.

Input Specification:

Each input file contains one test case. For each case, the first line gives two positive integers Nv (≤ 200), the number of vertices in the graph, and Ne, the number of undirected edges. Then Ne lines follow, each gives a pair of vertices of an edge. The vertices are numbered from 1 to Nv.

After the graph, there is another positive integer M (≤ 100). Then M lines of query follow, each first gives a positive number K (≤ Nv), then followed by a sequence of K distinct vertices. All the numbers in a line are separated by a space.

Output Specification:

For each of the M queries, print in a line Yes if the given subset of vertices can form a maximal clique; or if it is a clique but not a maximal clique, print Not Maximal; or if it is not a clique at all, print Not a Clique.

Sample Input:

8 10
5 6
7 8
6 4
3 6
4 5
2 3
8 2
2 7
5 3
3 4
6
4 5 4 3 6
3 2 8 7
2 2 3
1 1
3 4 3 6
3 3 2 1

Sample Output:

Yes
Yes
Yes
Yes
Not Maximal
Not a Clique
#include<bits/stdc++.h>
using namespace std;

const int MAXN = 200+10;
int N, M, Q;
int n, x;
bool visit[MAXN];
bool d[MAXN][MAXN];


bool check( vector< int > &v ){
	for(int i = 0; i < n; i++)
        for(int j = i+1; j < n; j++) if( !d[v[i]][v[j]] )
        	return false;   
  return true;
}

bool check2( vector< int > &v, int i ){
   for(int j = 0; j < v.size(); j++)
      if( !d[ v[j] ][ i ] )
         return false;
   return true;	
}

int main(){
   cin >> N >> M;
   for(int i = 0; i < M; i++){
      int a, b;
      scanf("%d%d", &a, &b);
      d[a][b] = d[b][a] = true;
   }
   cin >> Q;
   while(Q--){
   	  bool ok = false;
      vector< int > v;
      set< int > Myset;
      cin >> n;
      for(int i = 0; i < n; i++){
		     scanf("%d", &x);
		     v.push_back(x);
		     Myset.insert(x);
      }
      if( !check( v ) ) cout << "Not a Clique\n";
	    else{
	      for(int i = 1; i <= N; i++) if( !Myset.count(i) ){
	      	  if( check2( v, i ) ) {
	      	  	 ok = true;
	      	  	 break;
	      	  }
	      }
	      if(!ok) cout << "Yes\n";
        else cout << "Not Maximal\n";
      }
   }
   return 0;
}

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1143 Lowest Common Ancestor(30 分)

The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U and V as descendants.

A binary search tree (BST) is recursively defined as a binary tree which has the following properties:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
  • Both the left and right subtrees must also be binary search trees.

Given any two nodes in a BST, you are supposed to find their LCA.

Input Specification:

Each input file contains one test case. For each case, the first line gives two positive integers: M (≤ 1,000), the number of pairs of nodes to be tested; and N (≤ 10,000), the number of keys in the BST, respectively. In the second line, N distinct integers are given as the preorder traversal sequence of the BST. Then M lines follow, each contains a pair of integer keys U and V. All the keys are in the range of int.

Output Specification:

For each given pair of U and V, print in a line LCA of U and V is A. if the LCA is found and A is the key. But if A is one of U and V, print X is an ancestor of Y. where X is A and Y is the other node. If U or V is not found in the BST, print in a line ERROR: U is not found. or ERROR: V is not found. or ERROR: U and V are not found..

Sample Input:

6 8
6 3 1 2 5 4 8 7
2 5
8 7
1 9
12 -3
0 8
99 99

Sample Output:

LCA of 2 and 5 is 3.
8 is an ancestor of 7.
ERROR: 9 is not found.
ERROR: 12 and -3 are not found.
ERROR: 0 is not found.
ERROR: 99 and 99 are not found.
#include <bits/stdc++.h>
using namespace std;

map<int, bool> Mymap;

int main() {
    int m, n, u, v, a;
    scanf("%d %d", &m, &n);
    vector<int> pre(n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &pre[i]);
        Mymap[ pre[i] ] = true;
    }
    while( m-- ){
        scanf("%d %d", &u, &v);
        for(auto &i : pre) {
            a = i;
            if ( (a >= u && a <= v) || (a >= v && a <= u) ) break;
        } 
        if (Mymap[u] == false && Mymap[v] == false)  printf("ERROR: %d and %d are not found.\n", u, v);
        else if (Mymap[u] == false || Mymap[v] == false)  printf("ERROR: %d is not found.\n", Mymap[u] == false ? u : v);
        else if (a == u || a == v)  printf("%d is an ancestor of %d.\n", a, a == u ? v : u);
        else  printf("LCA of %d and %d is %d.\n", u, v, a);
    }
    return 0;
}

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1144 The Missing Number(20 分)

Given N integers, you are supposed to find the smallest positive integer that is NOT in the given list.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤10​5​​). Then N integers are given in the next line, separated by spaces. All the numbers are in the range of int.

Output Specification:

Print in a line the smallest positive integer that is missing from the input list.

Sample Input:

10
5 -25 9 6 1 3 4 2 5 17

Sample Output:

7
#include<bits/stdc++.h>
using namespace std;


int main(){
   int N, x;
   set< int > hash;
   cin >> N; 
   while( N-- ){
   	  scanf("%d", &x);
   	  if( x > 0) hash.insert(x);
   }
   int i = 1;
   for(auto it = hash.begin(); it != hash.end(); it++, i++)  if(*it != i){
      break;
   }
   cout << i << endl;
   return 0;
}

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1145 Hashing - Average Search Time(25 分)

The task of this problem is simple: insert a sequence of distinct positive integers into a hash table first. Then try to find another sequence of integer keys from the table and output the average search time (the number of comparisons made to find whether or not the key is in the table). The hash function is defined to be H(key)=key%TSize where TSize is the maximum size of the hash table. Quadratic probing (with positive increments only) is used to solve the collisions.

Note that the table size is better to be prime. If the maximum size given by the user is not prime, you must re-define the table size to be the smallest prime number which is larger than the size given by the user.

Input Specification:

Each input file contains one test case. For each case, the first line contains 3 positive numbers: MSize, N, and M, which are the user-defined table size, the number of input numbers, and the number of keys to be found, respectively. All the three numbers are no more than 10​4​​. Then N distinct positive integers are given in the next line, followed by M positive integer keys in the next line. All the numbers in a line are separated by a space and are no more than 10​5​​.

Output Specification:

For each test case, in case it is impossible to insert some number, print in a line X cannot be inserted. where X is the input number. Finally print in a line the average search time for all the M keys, accurate up to 1 decimal place.

Sample Input:

4 5 4
10 6 4 15 11
11 4 15 2

Sample Output:

15 cannot be inserted.
2.8
#include<bits/stdc++.h>
using namespace std;

bool isprime( int n ){
   if( n <= 1 )  return false;
   for(int i = 2; i <= sqrt(n)+0.5; i++){
      if( n % i == 0) return false;
   }
   return true;
}

int main(){
   int N, M, Q, x;
   cin >> N >> M >> Q;
   while( !isprime(N) ) N++;
   vector< int > hash(N);
   while( M-- ){
      bool ok = false;
      scanf("%d", &x);
      for(int j = 0; j < N; j++) if( !hash[ (x+j*j)%N ] ) {
          hash[ (x+j*j)%N ] = x;
          ok = true;
          break;
      }
      if( !ok ) printf("%d cannot be inserted.\n", x);
   }
   int cnt = 0;
   for(int i = 0; i < Q; i++){
      scanf("%d", &x);
      for(int j = 0; j <= N; j++){
         int v = hash[ (x+j*j)%N ];
         cnt++;
         if( !v || v == x)  break;
      }
   }
   printf("%.1f\n", cnt*1.0/Q);
   return 0;
}

 

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1146 Topological Order(25 分)

This is a problem given in the Graduate Entrance Exam in 2018: Which of the following is NOT a topological order obtained from the given directed graph? Now you are supposed to write a program to test each of the options.

gre.jpg

Input Specification:

Each input file contains one test case. For each case, the first line gives two positive integers N (≤ 1,000), the number of vertices in the graph, and M (≤ 10,000), the number of directed edges. Then M lines follow, each gives the start and the end vertices of an edge. The vertices are numbered from 1 to N. After the graph, there is another positive integer K (≤ 100). Then K lines of query follow, each gives a permutation of all the vertices. All the numbers in a line are separated by a space.

Output Specification:

Print in a line all the indices of queries which correspond to "NOT a topological order". The indices start from zero. All the numbers are separated by a space, and there must no extra space at the beginning or the end of the line. It is graranteed that there is at least one answer.

Sample Input:

6 8
1 2
1 3
5 2
5 4
2 3
2 6
3 4
6 4
5
1 5 2 3 6 4
5 1 2 6 3 4
5 1 2 3 6 4
5 2 1 6 3 4
1 2 3 4 5 6

Sample Output:

3 4
#include<bits/stdc++.h>
using namespace std;

vector< vector<int> > v, u;
vector< int > Degree, degree;

int main(){
   int N, M, Q, x, y;
   cin >> N >> M;
   v.resize( N+1 );
   Degree.resize( N+1 );
   while( M-- ){
      scanf("%d%d", &x, &y);
      v[x].push_back(y);
      Degree[y]++; 
   }
   
   cin >> Q;
   vector< int > Ans;
   for(int k = 0; k < Q; k++){
      degree = Degree; u = v;
      bool ok = true;
      for(int i = 0; i < N; i++){
         scanf("%d", &x);
         //x tutong
         if( degree[x] ) ok = false;
         if( !ok ) continue;
         for(int j = 0; j < u[x].size(); j++)
            degree[ u[x][j] ]--;
      }
      if( !ok ) Ans.push_back(k);
   }
   for(int i = 0; i < Ans.size(); i++)
      printf("%d%c", Ans[i], ( i == Ans.size()-1 ? '\n' : ' ') );
  
   return 0;
}

 

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

1147 Heaps(30 分)

In computer science, a heap is a specialized tree-based data structure that satisfies the heap property: if P is a parent node of C, then the key (the value) of P is either greater than or equal to (in a max heap) or less than or equal to (in a min heap) the key of C. A common implementation of a heap is the binary heap, in which the tree is a complete binary tree. (Quoted from Wikipedia at https://en.wikipedia.org/wiki/Heap_(data_structure))

Your job is to tell if a given complete binary tree is a heap.

Input Specification:

Each input file contains one test case. For each case, the first line gives two positive integers: M (≤ 100), the number of trees to be tested; and N (1 < N ≤ 1,000), the number of keys in each tree, respectively. Then M lines follow, each contains N distinct integer keys (all in the range of int), which gives the level order traversal sequence of a complete binary tree.

Output Specification:

For each given tree, print in a line Max Heap if it is a max heap, or Min Heap for a min heap, or Not Heap if it is not a heap at all. Then in the next line print the tree's postorder traversal sequence. All the numbers are separated by a space, and there must no extra space at the beginning or the end of the line.

Sample Input:

3 8
98 72 86 60 65 12 23 50
8 38 25 58 52 82 70 60
10 28 15 12 34 9 8 56

Sample Output:

Max Heap
50 60 65 72 12 23 86 98
Min Heap
60 58 52 38 82 70 25 8
Not Heap
56 12 34 28 9 8 15 10
#include<bits/stdc++.h>
using namespace std;

int m, n;
vector< int > v;

bool check(int i , int flag){
  int j = 2 * i;
  if( j > n ) return true;
  if( flag ){
    if( v[j] < v[i] ) return false;
    if( ++j <= n && v[j] < v[i] ) return false;
  }
  else{
    if( v[j] > v[i] ) return false;
    if( ++j <= n && v[j] > v[i] ) return false;
  }
  return check(2*i, flag) && check(2*i+1, flag);
}

void postOrder(int index) {
    if (index > n) return;
    postOrder(index*2);
    postOrder(index*2+1);
    printf("%d%s", v[index], index == 1 ? "\n" : " ");
}

int main() {
    cin >> m >> n;
    v.resize(n+1);
    while( m-- ){
       for(int i = 1; i <= n; i++) scanf("%d", &v[i]);
       if( check(1, 0) ) printf("Max Heap\n");
       else if( check(1, 1) ) printf("Min Heap\n");
       else printf("Not Heap\n");
       postOrder(1);
    }
    return 0;
}

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值