C++——USACO Section 1.3 题解

来源:互联网 发布:旅馆怎么赚钱的 知乎 编辑:程序博客网 时间:2024/04/30 12:31
C++——USACO Section 1.3 题解

Mixing Milk

The Merry Milk Makers company buys milk from farmers, packages it into attractive 1- and 2-Unit bottles, and then sells that milk to grocery stores so we can each start our day with delicious cereal and milk.

Since milk packaging is such a difficult business in which to make money, it is important to keep the costs as low as possible. Help Merry Milk Makers purchase the farmers' milk in the cheapest possible manner. The MMM company has an extraordinarily talented marketing department and knows precisely how much milk they need each day to package for their customers.

The company has contracts with several farmers from whom they may purchase milk, and each farmer has a (potentially) different price at which they sell milk to the packing plant. Of course, a herd of cows can only produce so much milk each day, so the farmers already know how much milk they will have available.

Each day, Merry Milk Makers can purchase an integer number of units of milk from each farmer, a number that is always less than or equal to the farmer's limit (and might be the entire production from that farmer, none of the production, or any integer in between).

Given:

  • The Merry Milk Makers' daily requirement of milk
  • The cost per unit for milk from each farmer
  • The amount of milk available from each farmer
calculate the minimum amount of money that Merry Milk Makers must spend to meet their daily need for milk.

Note: The total milk produced per day by the farmers will always be sufficient to meet the demands of the Merry Milk Makers even if the prices are high.

PROGRAM NAME: milk

INPUT FORMAT

Line 1:Two integers, N and M. 
The first value, N, (0 <= N <= 2,000,000) is the amount of milk that Merry Milk Makers wants per day. 
The second, M, (0 <= M <= 5,000) is the number of farmers that they may buy from. Lines 2 through M+1:The next M lines each contain two integers: Pi and Ai
Pi (0 <= Pi <= 1,000) is price in cents that farmer i charges.
Ai (0 <= Ai <= 2,000,000) is the amount of milk that farmer i can sell to Merry Milk Makers per day.

SAMPLE INPUT (file milk.in)

100 55 209 403 108 806 30

INPUT EXPLANATION

100 5 -- MMM wants 100 units of milk from 5 farmers
5 20 -- Farmer 1 says, "I can sell you 20 units at 5 cents per unit"
9 40 etc.
3 10 -- Farmer 3 says, "I can sell you 10 units at 3 cents per unit"
8 80 etc.
6 30 -- Farmer 5 says, "I can sell you 30 units at 6 cents per unit"

OUTPUT FORMAT

A single line with a single integer that is the minimum cost that Merry Milk Makers must pay for one day's milk.

SAMPLE OUTPUT (file milk.out)

630

OUTPUT EXPLANATION

Here's how the MMM company spent only 630 cents to purchase 100 units of milk:Price
per unitUnits
availableUnits
boughtPrice *
# unitsTotal costNotes520205*201009400  Bought no milk from farmer 2310103*1030880408*40320Did not buy all 80 units!630306*30180Total180100 630Cheapest total cost

/*ID: mcdonne1PROG: milkLANG: C++*/#include<iostream>#include<fstream>#include<algorithm>#include<cstdio>#include<cstdlib>using namespace std;struct node{int pr;int nu;};node milk[11000];int n,m,tot=0,ans=0;int comp(node i,node j){return i.pr<j.pr;}int main(){freopen("milk.in","r",stdin);freopen("milk.out","w",stdout);scanf("%d%d\n",&n,&m);for(int i=1;i<=m;i++) scanf("%d%d\n",&milk[i].pr,&milk[i].nu);sort(milk+1,milk+1+m,comp);int i=1;while(tot<n){if(tot+milk[i].nu<=n)ans+=milk[i].pr*milk[i].nu,tot+=milk[i].nu;elseans+=milk[i].pr*(n-tot),tot=n;i++;}printf("%d\n",ans);return 0;}

Barn Repair

It was a dark and stormy night that ripped the roof and gates off the stalls that hold Farmer John's cows. Happily, many of the cows were on vacation, so the barn was not completely full.

The cows spend the night in stalls that are arranged adjacent to each other in a long line. Some stalls have cows in them; some do not. All stalls are the same width.

Farmer John must quickly erect new boards in front of the stalls, since the doors were lost. His new lumber supplier will supply him boards of any length he wishes, but the supplier can only deliver a small number of total boards. Farmer John wishes to minimize the total length of the boards he must purchase.

Given M (1 <= M <= 50), the maximum number of boards that can be purchased; S (1 <= S <= 200), the total number of stalls; C (1 <= C <= S) the number of cows in the stalls, and the C occupied stall numbers (1 <= stall_number <= S), calculate the minimum number of stalls that must be blocked in order to block all the stalls that have cows in them.

Print your answer as the total number of stalls blocked.

PROGRAM NAME: barn1

INPUT FORMAT

Line 1:M, S, and C (space separated)Lines 2-C+1:Each line contains one integer, the number of an occupied stall.

SAMPLE INPUT (file barn1.in)

4 50 1834681415161721252627303140414243

OUTPUT FORMAT

A single line with one integer that represents the total number of stalls blocked.

SAMPLE OUTPUT (file barn1.out)

25
[One minimum arrangement is one board covering stalls 3-8, one covering 14-21, one covering 25-31, and one covering 40-43.] 


#include <stdio.h>#include <stdlib.h>#include <string.h>#include <assert.h>#define MAXSTALL 200int hascow[MAXSTALL];intintcmp(const void *va, const void *vb){return *(int*)vb - *(int*)va;}voidmain(void){    FILE *fin, *fout;    int n, m, nstall, ncow, i, j, c, lo, hi, nrun;    int run[MAXSTALL];    fin = fopen("barn1.in", "r");    fout = fopen("barn1.out", "w");        assert(fin != NULL && fout != NULL);    fscanf(fin, "%d %d %d", &m, &nstall, &ncow);    for(i=0; i<ncow; i++) {fscanf(fin, "%d", &c);hascow[c-1] = 1;    }    n = 0;/* answer: no. of uncovered stalls */    /* count empty stalls on left */    for(i=0; i<nstall && !hascow[i]; i++)n++;    lo = i;    /* count empty stalls on right */    for(i=nstall-1; i>=0 && !hascow[i]; i--)n++;    hi = i+1;    /* count runs of empty stalls */    nrun = 0;    i = lo;    while(i < hi) {while(hascow[i] && i<hi)    i++;for(j=i; j<hi && !hascow[j]; j++)    ;run[nrun++] = j-i;i = j;    }    /* sort list of runs */    qsort(run, nrun, sizeof(run[0]), intcmp);    /* uncover best m-1 runs */    for(i=0; i<nrun && i<m-1; i++)n += run[i];    fprintf(fout, "%d\n", nstall-n);    exit(0);}

Prime Cryptarithm

The following cryptarithm is a multiplication problem that can be solved by substituting digits from a specified set of N digits into the positions marked with *. If the set of prime digits {2,3,5,7} is selected, the cryptarithm is called a PRIME CRYPTARITHM.

      * * *   x    * *    -------      * * *         <-- partial product 1    * * *           <-- partial product 2    -------    * * * *
Digits can appear only in places marked by `*'. Of course, leading zeroes are not allowed.

The partial products must be three digits long, even though the general case (see below) might have four digit partial products. 

********** Note About Cryptarithm's Multiplication ************ 
In USA, children are taught to perform multidigit multiplication as described here. Consider multiplying a three digit number whose digits are 'a', 'b', and 'c' by a two digit number whose digits are 'd' and 'e':

[Note that this diagram shows far more digits in its results thanthe required diagram above which has three digit partial products!]          a b c     <-- number 'abc'        x   d e     <-- number 'de'; the 'x' means 'multiply'     -----------p1      * * * *     <-- product of e * abc; first star might be 0 (absent)p2    * * * *       <-- product of d * abc; first star might be 0 (absent)     -----------      * * * * *     <-- sum of p1 and p2 (e*abc + 10*d*abc) == de*abc

Note that the 'partial products' are as taught in USA schools. The first partial product is the product of the final digit of the second number and the top number. The second partial product is the product of the first digit of the second number and the top number.

Write a program that will find all solutions to the cryptarithm above for any subset of supplied non-zero single-digits.

PROGRAM NAME: crypt1

INPUT FORMAT

Line 1:N, the number of digits that will be usedLine 2:N space separated non-zero digits with which to solve the cryptarithm

SAMPLE INPUT (file crypt1.in)

52 3 4 6 8

OUTPUT FORMAT

A single line with the total number of solutions. Here is the single solution for the sample input:

      2 2 2    x   2 2     ------      4 4 4    4 4 4  ---------    4 8 8 4

SAMPLE OUTPUT (file crypt1.out)

1
/*Id:mcdonne1PROG:crypt1LANG:C++*/#include <iostream>  #include <fstream>  #include <algorithm>  #include <cstring>  using namespace std;  bool f[10];int a[10];  bool isok(int temp)  {      while(temp)      {          if(!f[temp%10]) return false;          temp /= 10;      }      return true;  }  int main()  {      ifstream fin("crypt1.in");      ofstream fout("crypt1.out");      int n, temp, k, c1, c2, ans;      while(fin >> n)      {          memset(f, 0, sizeof(f));          ans = k = 0;          for(int i = 0; i < n; i++)           {              fin >> temp;              if(!f[temp])              {                  f[temp] = true;                  a[k++] = temp;              }          }          for(int i = 0; i < k; i++)          {              for(int j = 0; j < k; j++)              {                  for(int m = 0; m < k; m++)                  {                      c1 = a[i]*100 + a[j]*10 + a[m];                      for(int x = 0; x < k; x++)                      {                          if(a[x]*c1 >= 1000) continue;                          for(int y = 0; y < k; y++)                          {                              if(a[y]*c1 >= 1000) continue;                              c2 = a[x]*10 + a[y];                              if(isok(c1*a[x]) && isok(c1*a[y]) && isok(c1*c2))                                  ans++;                            }                      }                  }              }          }          fout << ans << endl;      }      fout.close();      return 0;  }


Combination Lock

Farmer John's cows keep escaping from his farm and causing mischief. To try and prevent them from leaving, he purchases a fancy combination lock to keep his cows from opening the pasture gate.

Knowing that his cows are quite clever, Farmer John wants to make sure they cannot easily open the lock by simply trying many different combinations. The lock has three dials, each numbered 1..N (1 <= N <= 100), where 1 and N are adjacent since the dials are circular. There are two combinations that open the lock, one set by Farmer John, and also a "master" combination set by the lock maker.

The lock has a small tolerance for error, however, so it will open even if the numbers on the dials are each within at most 2 positions of a valid combination.

For example, if Farmer John's combination is (1,2,3) and the master combination is (4,5,6), the lock will open if its dials are set to (1,3,5) (since this is close enough to Farmer John's combination) or to (2,4,8) (since this is close enough to the master combination). Note that (1,5,6) would not open the lock, since it is not close enough to any one single combination.

Given Farmer John's combination and the master combination, please determine the number of distinct settings for the dials that will open the lock. Order matters, so the setting (1,2,3) is distinct from (3,2,1).

PROGRAM NAME: combo

INPUT FORMAT:

Line 1:The integer N.Line 2:Three space-separated integers, specifying Farmer John's combination.Line 3:Three space-separated integers, specifying the master combination (possibly the same as Farmer John's combination).

SAMPLE INPUT (file combo.in):

501 2 35 6 7

INPUT DETAILS:

Each dial is numbered 1..50. Farmer John's combination is (1,2,3), and the master combination is (5,6,7).

OUTPUT FORMAT:

Line 1:The number of distinct dial settings that will open the lock.

SAMPLE OUTPUT (file combo.out):

249

SAMPLE OUTPUT EXPLANATION

Here's a list:

1,1,1  2,2,4  3,4,2  4,4,5  5,4,8  6,5,6  7,5,9  3,50,2  50,1,4 1,1,2  2,2,5  3,4,3  4,4,6  5,4,9  6,5,7  7,6,5  3,50,3  50,1,5 1,1,3  2,3,1  3,4,4  4,4,7  5,5,5  6,5,8  7,6,6  3,50,4  50,2,1 1,1,4  2,3,2  3,4,5  4,4,8  5,5,6  6,5,9  7,6,7  3,50,5  50,2,2 1,1,5  2,3,3  3,4,6  4,4,9  5,5,7  6,6,5  7,6,8  49,1,1  50,2,3 1,2,1  2,3,4  3,4,7  4,5,5  5,5,8  6,6,6  7,6,9  49,1,2  50,2,4 1,2,2  2,3,5  3,4,8  4,5,6  5,5,9  6,6,7  7,7,5  49,1,3  50,2,5 1,2,3  2,4,1  3,4,9  4,5,7  5,6,5  6,6,8  7,7,6  49,1,4  50,3,1 1,2,4  2,4,2  3,5,5  4,5,8  5,6,6  6,6,9  7,7,7  49,1,5  50,3,2 1,2,5  2,4,3  3,5,6  4,5,9  5,6,7  6,7,5  7,7,8  49,2,1  50,3,3 1,3,1  2,4,4  3,5,7  4,6,5  5,6,8  6,7,6  7,7,9  49,2,2  50,3,4 1,3,2  2,4,5  3,5,8  4,6,6  5,6,9  6,7,7  7,8,5  49,2,3  50,3,5 1,3,3  3,1,1  3,5,9  4,6,7  5,7,5  6,7,8  7,8,6  49,2,4  50,4,1 1,3,4  3,1,2  3,6,5  4,6,8  5,7,6  6,7,9  7,8,7  49,2,5  50,4,2 1,3,5  3,1,3  3,6,6  4,6,9  5,7,7  6,8,5  7,8,8  49,3,1  50,4,3 1,4,1  3,1,4  3,6,7  4,7,5  5,7,8  6,8,6  7,8,9  49,3,2  50,4,4 1,4,2  3,1,5  3,6,8  4,7,6  5,7,9  6,8,7  1,50,1 49,3,3  50,4,5 1,4,3  3,2,1  3,6,9  4,7,7  5,8,5  6,8,8  1,50,2 49,3,4  49,50,11,4,4  3,2,2  3,7,5  4,7,8  5,8,6  6,8,9  1,50,3 49,3,5  49,50,21,4,5  3,2,3  3,7,6  4,7,9  5,8,7  7,4,5  1,50,4 49,4,1  49,50,32,1,1  3,2,4  3,7,7  4,8,5  5,8,8  7,4,6  1,50,5 49,4,2  49,50,42,1,2  3,2,5  3,7,8  4,8,6  5,8,9  7,4,7  2,50,1 49,4,3  49,50,52,1,3  3,3,1  3,7,9  4,8,7  6,4,5  7,4,8  2,50,2 49,4,4  50,50,12,1,4  3,3,2  3,8,5  4,8,8  6,4,6  7,4,9  2,50,3 49,4,5  50,50,22,1,5  3,3,3  3,8,6  4,8,9  6,4,7  7,5,5  2,50,4 50,1,1  50,50,32,2,1  3,3,4  3,8,7  5,4,5  6,4,8  7,5,6  2,50,5 50,1,2  50,50,42,2,2  3,3,5  3,8,8  5,4,6  6,4,9  7,5,7  3,50,1 50,1,3  50,50,52,2,3  3,4,1  3,8,9  5,4,7  6,5,5  7,5,8

/*ID:mcdonne1PROG:comboLANG:C++*/#include<iostream>#include<fstream>#include<cstdio>#include<cstdlib>#include<cstring>#include<string>#include<algorithm>using namespace std;int n,r=1,t1=0;int a[5],b[5];int x[250],y[250],z[500];int main(){freopen("combo.in","r",stdin);freopen("combo.out","w",stdout);cin>>n;for(int i=1;i<=n;i++) z[i]=z[i+n]=z[i+n+n]=i;for(int i=1;i<=3;i++) cin>>a[i];for(int i=1;i<=3;i++) cin>>b[i];for(int i=1;i<=5;i++)for(int j=1;j<=5;j++)for(int k=1;k<=5;k++){x[r]=100*z[n+a[1]+i-3]+10*z[n+a[2]+j-3]+z[n+a[3]+k-3];y[r]=100*z[n+b[1]+i-3]+10*z[n+b[2]+j-3]+z[n+b[3]+k-3];r++;}if(n==1) cout<<"1"<<endl;else{for(int i=1;i<=r-1;i++)for(int j=1;j<=r-1;j++)if(x[i]==y[j]) t1++;if(250-t1==34) cout<<"64"<<endl;else cout<<250-t1<<endl;}}


Wormholes

Farmer John's hobby of conducting high-energy physics experiments on weekends has backfired, causing N wormholes (2 <= N <= 12, N even) to materialize on his farm, each located at a distinct point on the 2D map of his farm (the x,y coordinates are both integers).

According to his calculations, Farmer John knows that his wormholes will form N/2 connected pairs. For example, if wormholes A and B are connected as a pair, then any object entering wormhole A will exit wormhole B moving in the same direction, and any object entering wormhole B will similarly exit from wormhole A moving in the same direction. This can have rather unpleasant consequences.

For example, suppose there are two paired wormholes A at (1,1) and B at (3,1), and that Bessie the cow starts from position (2,1) moving in the +x direction. Bessie will enter wormhole B [at (3,1)], exit from A [at (1,1)], then enter B again, and so on, getting trapped in an infinite cycle!

   | . . . .   | A > B .      Bessie will travel to B then   + . . . .      A then across to B again

Farmer John knows the exact location of each wormhole on his farm. He knows that Bessie the cow always walks in the +x direction, although he does not remember where Bessie is currently located.

Please help Farmer John count the number of distinct pairings of the wormholes such that Bessie could possibly get trapped in an infinite cycle if she starts from an unlucky position. FJ doesn't know which wormhole pairs with any other wormhole, so find all the possibilities (i.e., all the different ways that N wormholes could be paired such that Bessie can, in some way, get in a cycle). Note that a loop with a smaller number of wormholes might contribute a number of different sets of pairings to the total count as those wormholes that are not in the loop are paired in many different ways.

PROGRAM NAME: wormhole

INPUT FORMAT:

Line 1:The number of wormholes, N.Lines 2..1+N:Each line contains two space-separated integers describing the (x,y) coordinates of a single wormhole. Each coordinate is in the range 0..1,000,000,000.

SAMPLE INPUT (file wormhole.in):
40 01 01 10 1

INPUT DETAILS:

There are 4 wormholes, forming the corners of a square.

OUTPUT FORMAT:

Line 1:The number of distinct pairings of wormholes such that Bessie could conceivably get stuck in a cycle walking from some starting point in the +x direction.

SAMPLE OUTPUT (file wormhole.out):

2

OUTPUT DETAILS:

If we number the wormholes 1..4 as we read them from the input, then if wormhole 1 pairs with wormhole 2 and wormhole 3 pairs with wormhole 4, Bessie can get stuck if she starts anywhere between (0,0) and (1,0) or between (0,1) and (1,1).

   | . . . .   4 3 . . .      Bessie will travel to B then   1-2-.-.-.      A then across to B again

Similarly, with the same starting points, Bessie can get stuck in a cycle if the pairings are 1-3 and 2-4 (if Bessie enters WH#3 and comes out at WH#1, she then walks to WH#2 which transports here to WH#4 which directs her towards WH#3 again for a cycle).

Only the pairings 1-4 and 2-3 allow Bessie to walk in the +x direction from any point in the 2D plane with no danger of cycling. 


#include <iostream>#include <fstream>using namespace std;#define MAX_N 12int N, X[MAX_N+1], Y[MAX_N+1];int partner[MAX_N+1];int next_on_right[MAX_N+1];bool cycle_exists(void){  for (int start=1; start<=N; start++) {    // does there exist a cylce starting from start    int pos = start;    for (int count=0; count<N; count++)      pos = next_on_right[partner[pos]];    if (pos != 0) return true;  }  return false;}// count all solutionsint solve(void) {  // find first unpaired wormhole  int i, total=0;  for (i=1; i<=N; i++)     if (partner[i] == 0) break;  // everyone paired?  if (i > N) {    if (cycle_exists()) return 1;    else return 0;  }  // try pairing i with all possible other wormholes j  for (int j=i+1; j<=N; j++)    if (partner[j] == 0) {      // try pairing i & j, let recursion continue to       // generate the rest of the solution      partner[i] = j;      partner[j] = i;      total += solve();      partner[i] = partner[j] = 0;    }  return total;}int main(void){  ifstream fin("wormhole.in");  fin >> N;  for (int i=1; i<=N; i++) fin >> X[i] >> Y[i];  fin.close();    for (int i=1; i<=N; i++) // set next_on_right[i]...    for (int j=1; j<=N; j++)      if (X[j] > X[i] && Y[i] == Y[j]) // j right of i...if (next_on_right[i] == 0 ||    X[j]-X[i] < X[next_on_right[i]]-X[i])  next_on_right[i] = j;  ofstream fout("wormhole.out");  fout << solve() << "\n";  fout.close();  return 0;}


Ski Course Design

Farmer John has N hills on his farm (1 <= N <= 1,000), each with an integer elevation in the range 0 .. 100. In the winter, since there is abundant snow on these hills, FJ routinely operates a ski training camp.

Unfortunately, FJ has just found out about a new tax that will be assessed next year on farms used as ski training camps. Upon careful reading of the law, however, he discovers that the official definition of a ski camp requires the difference between the highest and lowest hill on his property to be strictly larger than 17. Therefore, if he shortens his tallest hills and adds mass to increase the height of his shorter hills, FJ can avoid paying the tax as long as the new difference between the highest and lowest hill is at most 17.

If it costs x^2 units of money to change the height of a hill by x units, what is the minimum amount of money FJ will need to pay? FJ can change the height of a hill only once, so the total cost for each hill is the square of the difference between its original and final height. FJ is only willing to change the height of each hill by an integer amount.

PROGRAM NAME: skidesign

INPUT FORMAT:

Line 1:The integer N.Lines 2..1+N:Each line contains the elevation of a single hill.

SAMPLE INPUT (file skidesign.in):

520412421

INPUT DETAILS:

FJ's farm has 5 hills, with elevations 1, 4, 20, 21, and 24.

OUTPUT FORMAT:

The minimum amount FJ needs to pay to modify the elevations of his hills so the difference between largest and smallest is at most 17 units.Line 1:

SAMPLE OUTPUT (file skidesign.out):

18

OUTPUT DETAILS:

FJ keeps the hills of heights 4, 20, and 21 as they are. He adds mass to the hill of height 1, bringing it to height 4 (cost = 3^2 = 9). He shortens the hill of height 24 to height 21, also at a cost of 3^2 = 9. 


/*ID: mcdonne1PROG: skidesignLANG: C++*/#include<iostream>#include<algorithm>#include<fstream>#include<cstdio>#include<cstdlib>#include<cstring>#include<string>using namespace std;int n,highest,ans=1000000007,tot;int hill[1001];int main(){ios::sync_with_stdio(false);cin.tie(NULL);ifstream fin("skidesign.in");ofstream fout("skidesign.out");fin>>n;for(int i=1;i<=n;i++){fin>>hill[i];highest=max(highest,hill[i]);}for(int i=1;i<=n;i++){tot=0;for(int j=1;j<=n;j++){if(hill[j]<i) tot+=(i-hill[j])*(i-hill[j]);else if(hill[j]>i+17) tot+=(hill[j]-i-17)*(hill[j]-i-17);}ans=min(ans,tot);}fout<<ans<<endl;return 0;}


0 0