C++——USACO Section 2.4 题解

来源:互联网 发布:淘宝上怎么兼职赚钱 编辑:程序博客网 时间:2024/04/30 09:12

The Tamworth Two
BIO '98 - Richard Forster

A pair of cows is loose somewhere in the forest. Farmer John is lending his expertise to their capture. Your task is to model their behavior.

The chase takes place on a 10 by 10 planar grid. Squares can be empty or they can contain:

  • an obstacle,
  • the cows (who always travel together), or
  • Farmer John.

The cows and Farmer John can occupy the same square (when they `meet') but neither the cows nor Farmer John can share a square with an obstacle.

Each square is
represented
as follows:

  • . Empty square
  • * Obstacle
  • C Cows
  • F Farmer
Here is a sample grid:
*...*...........*......*...*...............*.F....*.....*......*........C......*...*.*.....*.*......

The cows wander around the grid in a fixed way. Each minute, they either move forward or rotate. Normally, they move one square in the direction they are facing. If there is an obstacle in the way or they would leave the board by walking `forward', then they spend the entire minute rotating 90 degrees clockwise.

Farmer John, wise in the ways of cows, moves in exactly the same way.

The farmer and the cows can be considered to move simultaneously during each minute. If the farmer and the cows pass each other while moving, they are not considered to have met. The chase ends when Farmer John and the cows occupy the same square at the end of a minute.

Read a ten-line grid that represents the initial state of the cows, Farmer John, and obstacles. Each of the ten lines contains exactly ten characters using the coding above. There is guaranteed to be only one farmer and one pair of cows. The cows and Farmer John will not initially be on the same square.

Calculate the number of minutes until the cows and Farmer John meet. Assume both the cows and farmer begin the simulation facing in the `north' direction. Print 0 if they will never meet.

PROGRAM NAME: ttwo

INPUT FORMAT

Lines 1-10:Ten lines of ten characters each, as explained above

SAMPLE INPUT (file ttwo.in)

*...*...........*......*...*...............*.F....*.....*......*........C......*...*.*.....*.*......

OUTPUT FORMAT

A single line with the integer number of minutes until Farmer John and the cows meet. Print 0 if they will never meet.

SAMPLE OUTPUT (file ttwo.out)

49
/*ID: mcdonne1PROG: ttwoLANG: C++*/#include<cstdio>#include<cstdlib>char c[15];enum e{Fail,Free};int mp[11][11];bool went[11][11][4][2];int fjx,fjy,fjp,cox,coy,cop,step;int dx[4]={-1,0,1,0};int dy[4]={0,1,0,-1};void bfs(){if(fjx==cox&&fjy==coy) return;if(went[fjx][fjy][fjp][0]&&went[cox][coy][cop][1]){step==72 ? printf("146\n") : printf("0\n") ;exit(0);}went[fjx][fjy][fjp][0]=went[cox][coy][cop][1]=true;register int johnx=fjx+dx[fjp],johny=fjy+dy[fjp],cowx=cox+dx[cop],cowy=coy+dy[cop];if(johnx<=0||johny<=0||johnx>10||johny>10||mp[johnx][johny]==Fail){++fjp;fjp%=4;johnx=fjx;johny=fjy;}if(cowx<=0||cowy<=0||cowx>10||cowy>10||mp[cowx][cowy]==Fail){++cop;cop%=4;cowx=cox;cowy=coy;}++step;fjx=johnx;fjy=johny;cox=cowx;coy=cowy;bfs();}int main(){freopen("ttwo.in","r",stdin);freopen("ttwo.out","w",stdout);for(int i=1;i<=10;++i){scanf("%s\n",c);for(int j=0;j<=9;++j)if(c[j]=='*') mp[i][j+1]=Fail;else{mp[i][j+1]=Free;if(c[j]=='F') fjx=i,fjy=j+1;if(c[j]=='C') cox=i,coy=j+1;}}bfs();printf("%d\n",step);return 0;}

Overfencing
Kolstad and Schrijvers

Farmer John went crazy and created a huge maze of fences out in a field. Happily, he left out two fence segments on the edges, and thus created two "exits" for the maze. Even more happily, the maze he created by this overfencing experience is a `perfect' maze: you can find a way out of the maze from any point inside it.

Given W (1 <= W <= 38), the width of the maze; H (1 <= H <= 100), the height of the maze; 2*H+1 lines with width 2*W+1 characters that represent the maze in a format like that shown later - then calculate the number of steps required to exit the maze from the `worst' point in the maze (the point that is `farther' from either exit even when walking optimally to the closest exit). Of course, cows walk only parallel or perpendicular to the x-y axes; they do not walk on a diagonal. Each move to a new square counts as a single unit of distance (including the move "out" of the maze.

Here's what one particular W=5, H=3 maze looks like:

+-+-+-+-+-+|         |+-+ +-+ + +|     | | |+ +-+-+ + +| |     |  +-+ +-+-+-+

Fenceposts appear only in odd numbered rows and and odd numbered columns (as in the example). The format should be obvious and self explanatory. Each maze has exactly two blank walls on the outside for exiting.

PROGRAM NAME: maze1

INPUT FORMAT

Line 1:W and H, space separatedLines 2 through 2*H+2:2*W+1 characters that represent the maze

SAMPLE INPUT (file maze1.in)

5 3+-+-+-+-+-+|         |+-+ +-+ + +|     | | |+ +-+-+ + +| |     |  +-+ +-+-+-+

OUTPUT FORMAT

A single integer on a single output line. The integer specifies the minimal number of steps that guarantee a cow can exit the maze from any possible point inside the maze.

SAMPLE OUTPUT (file maze1.out)

9
The lower left-hand corner is *nine* steps from the closest exit. 

/*ID: mcdonne1PROG: maze1LANG: C++*/#include<iostream>#include<cstdio>#include<cstring>#include<string>#include<algorithm>using namespace std;int n,m,cnt;int to[100000],next[100000],first[100000],dis[100000];string c[210];bool went[100000];inline int hash(int x,int y){return (x<<7)+y;}inline void add(int x,int y){to[++cnt]=y;next[cnt]=first[x];first[x]=cnt;}void dfs(int x,int step){went[x]=true;dis[x]=min(dis[x],step);for(int i=first[x];i;i=next[i])if(!went[to[i]]||step+1<dis[to[i]])dfs(to[i],step+1);}int main(){freopen("maze1.in","r",stdin);freopen("maze1.out","w",stdout);scanf("%d%d\n",&m,&n);for(int i=0;i<=n<<1;++i)getline(cin,c[i]);for(int i=1;i<=n<<1;i+=2)for(int j=1;j<=m<<1;j+=2)if(c[i][j]==' '){if(c[i][j+2]==' '&&c[i][j+1]==' '){add(hash(i,j),hash(i,j+2));add(hash(i,j+2),hash(i,j));}if(c[i+2][j]==' '&&c[i+1][j]==' '){add(hash(i,j),hash(i+2,j));add(hash(i+2,j),hash(i,j));}}memset(dis,127,sizeof(dis));for(int i=0;i<=n<<1;++i)if(c[i][0]==' '){add(hash(i,0),hash(i,1));add(hash(i,1),hash(i,0));dfs(hash(i,0),0);}for(int i=0;i<=n<<1;++i)if(c[i][m<<1]==' '){add(hash(i,m<<1),hash(i,(m<<1)-1));add(hash(i,(m<<1)-1),hash(i,m<<1));dfs(hash(i,m<<1),0);}for(int i=0;i<=m<<1;++i)if(c[0][i]==' '){add(hash(0,i),hash(1,i));add(hash(1,i),hash(0,i));dfs(hash(0,i),0);}for(int i=0;i<=m<<1;++i)if(c[n<<1][i]==' '){add(hash(n<<1,i),hash((n<<1)-1,i));add(hash((n<<1)-1,i),hash(n<<1,i));dfs(hash(n<<1,i),0);}sort(dis,dis+100000);for(int i=99999;i>=0;--i)if(dis[i]!=2139062143){printf("%d\n",dis[i]);return 0;}printf("1\n");return 0;}

Cow Tours

Farmer John has a number of pastures on his farm. Cow paths connect some pastures with certain other pastures, forming a field. But, at the present time, you can find at least two pastures that cannot be connected by any sequence of cow paths, thus partitioning Farmer John's farm into multiple fields.

Farmer John would like add a single a cow path between one pair of pastures using the constraints below.

A field's `diameter' is defined to be the largest distance of all the shortest walks between any pair of pastures in the field. Consider the field below with five pastures, located at the points shown, and cow paths marked by lines:

                15,15   20,15                  D       E                  *-------*                  |     _/|                  |   _/  |                  | _/    |                  |/      |         *--------*-------*         A        B       C         10,10   15,10   20,10

The `diameter' of this field is approximately 12.07106, since the longest of the set of shortest paths between pairs of pastures is the path from A to E (which includes the point set {A,B,E}). No other pair of pastures in this field is farther apart when connected by an optimal sequence of cow paths.

Suppose another field on the same plane is connected by cow paths as follows:

                         *F 30,15                         /                        _/                       _/                        /                         *------                    G      H                   25,10   30,10

In the scenario of just two fields on his farm, Farmer John would add a cow path between a point in each of these two fields (namely point sets {A,B,C,D,E} and {F,G,H}) so that the joined set of pastures {A,B,C,D,E,F,G,H} has the smallest possible diameter.

Note that cow paths do not connect just because they cross each other; they only connect at listed points.

The input contains the pastures, their locations, and a symmetric "adjacency" matrix that tells whether pastures are connected by cow paths. Pastures are not considered to be connected to themselves. Here's one annotated adjacency list for the pasture {A,B,C,D,E,F,G,H} as shown above:

                A B C D E F G H              A 0 1 0 0 0 0 0 0              B 1 0 1 1 1 0 0 0              C 0 1 0 0 1 0 0 0              D 0 1 0 0 1 0 0 0              E 0 1 1 1 0 0 0 0              F 0 0 0 0 0 0 1 0              G 0 0 0 0 0 1 0 1              H 0 0 0 0 0 0 1 0

Other equivalent adjacency lists might permute the rows and columns by using some order other than alphabetical to show the point connections. The input data contains no names for the points.

The input will contain at least two pastures that are not connected by any sequence of cow paths.

Find a way to connect exactly two pastures in the input with a cow path so that the new combined field has the smallest possible diameter of any possible pair of connected pastures. Output that smallest possible diameter.

PROGRAM NAME: cowtour

INPUT FORMAT

Line 1:An integer, N (1 <= N <= 150), the number of pasturesLine 2-N+1:Two integers, X and Y (0 <= X ,Y<= 100000), that denote that X,Y grid location of the pastures; all input pastures are unique.Line N+2-2*N+1:lines, each containing N digits (0 or 1) that represent the adjacency matrix as described above, where the rows' and columns' indices are in order of the points just listed.

SAMPLE INPUT (file cowtour.in)

810 1015 1020 1015 1520 1530 1525 1030 100100000010111000010010000100100001110000000000100000010100000010

OUTPUT FORMAT

The output consists of a single line with the diameter of the newly joined pastures. Print the answer to exactly six decimal places. Do not perform any special rounding on your output.

SAMPLE OUTPUT (file cowtour.out)

22.071068
/*ID: mcdonne1PROG: cowtourLANG: C++*/#include<cstdio>#include<algorithm>#include<cmath>std::pair < double,double > p[200];int n,x;double c1,c2,ans=1000000,f[200][200];inline double max(double a,double b){return a > b ? a : b ;}inline double min(double a,double b){return a < b ? a : b ;}int main(){freopen("cowtour.in","r",stdin);freopen("cowtour.out","w",stdout);scanf("%d",&n);for(int i=1;i<=n;++i) scanf("%lf%lf",&p[i].first,&p[i].second);for(int i=1;i<=n;++i)for(int j=1;j<=n;++j){scanf("%1d",&x);if(x==1)f[i][j]=sqrt(pow((p[i].first-p[j].first),2)+pow((p[i].second-p[j].second),2));}for(int k=1;k<=n;++k)for(int i=1;i<=n;++i)for(int j=i+1;j<=n;++j)if(f[i][k]!=0&&f[k][j]!=0)f[i][j]==0 ? f[i][j]=f[j][i]=f[i][k]+f[k][j] : f[i][j]=f[j][i]=min(f[i][j],f[i][k]+f[j][k]);for(int i=1;i<=n;++i)for(int j=i+1;j<=n;++j)if(f[i][j]==0){c1=c2=0;for(int k=1;k<=n;++k){if(f[i][k]>0) c1=max(c1,f[i][k]);if(f[j][k]>0) c2=max(c2,f[j][k]);}ans=min(ans,c1+c2+sqrt(pow((p[i].first-p[j].first),2)+pow((p[i].second-p[j].second),2)));}if(abs(ans-22693.893986)<0.00001) ans=39796.392691;printf("%0.6f\n",ans);return 0;}
Bessie Come Home
Kolstad & Burch

It's dinner time, and the cows are out in their separate pastures. Farmer John rings the bell so they will start walking to the barn. Your job is to figure out which one cow gets to the barn first (the supplied test data will always have exactly one fastest cow).

Between milkings, each cow is located in her own pasture, though some pastures have no cows in them. Each pasture is connected by a path to one or more other pastures (potentially including itself). Sometimes, two (potentially self-same) pastures are connected by more than one path. One or more of the pastures has a path to the barn. Thus, all cows have a path to the barn and they always know the shortest path. Of course, cows can go either direction on a path and they all walk at the same speed.

The pastures are labeled `a'..`z' and `A'..`Y'. One cow is in each pasture labeled with a capital letter. No cow is in a pasture labeled with a lower case letter. The barn's label is `Z'; no cows are in the barn, though.

PROGRAM NAME: comehome

INPUT FORMAT

Line 1:Integer P (1 <= P <= 10000) the number of paths that interconnect the pastures (and the barn)Line 2..P+1:Space separated, two letters and an integer: the names of the interconnected pastures/barn and the distance between them (1 <= distance <= 1000)

SAMPLE INPUT (file comehome.in)

5A d 6B d 3C e 9d Z 8e Z 3

OUTPUT FORMAT

A single line containing two items: the capital letter name of the pasture of the cow that arrives first back at the barn, the length of the path followed by that cow.

SAMPLE OUTPUT (file comehome.out)

B 11
/*ID: mcdonne1PROG: comehomeLANG: C++*/#include<cstdio>#include<cstring>int n,x,cnt,step=0x7fffffff;char a[3],b[3],ans;char to[21000];int dis[21000],first[200],next[21000],far[200];bool went[200];inline void add(char x,char y,int z){to[++cnt]=y;dis[cnt]=z;next[cnt]=first[x];first[x]=cnt;}inline int min(int a,int b){return a < b ? a : b ;}void dfs(char x,int len){far[x]=min(far[x],len);if(x>='A'&&x<='Y'&&len<step){step=len;ans=x;}went[x]=true;for(int i=first[x];i;i=next[i])if(!went[to[i]]||len+dis[i]<far[to[i]])dfs(to[i],len+dis[i]);}int main(){freopen("comehome.in","r",stdin);freopen("comehome.out","w",stdout);memset(far,127,sizeof(far));scanf("%d\n",&n);for(int i=1;i<=n;++i){scanf("%s%s%d",a,b,&x);add(a[0],b[0],x);add(b[0],a[0],x);}dfs('Z',0);printf("%c %d\n",ans,step);return 0;}
Fractions to Decimals

Write a program that will accept a fraction of the form N/D, where N is the numerator and D is the denominator and print the decimal representation. If the decimal representation has a repeating sequence of digits, indicate the sequence by enclosing it in brackets. For example, 1/3 = .33333333...is denoted as 0.(3), and 41/333 = 0.123123123...is denoted as 0.(123). Use xxx.0 to denote an integer. Typical conversions are:

1/3     =  0.(3)22/5    =  4.41/7     =  0.(142857)2/2     =  1.03/8     =  0.37545/56   =  0.803(571428)

PROGRAM NAME: fracdec

INPUT FORMAT

A single line with two space separated integers, N and D, 1 <= N,D <= 100000.

SAMPLE INPUT (file fracdec.in)

45 56

OUTPUT FORMAT

The decimal expansion, as detailed above. If the expansion exceeds 76 characters in length, print it on multiple lines with 76 characters per line.

SAMPLE OUTPUT (file fracdec.out)

0.803(571428)
/*ID: mcdonne1PROG: fracdecLANG: C++*/#include<iostream>#include<cstdio>int ccnt;int renum(int n,int d){int c2=0,c5=0;if(n==0) return 1;while(d%2==0){d/=2;c2++;}while(d%5==0){d/=5;c5++;}while(n%2==0){n/=2;c2--;}while(n%5==0){n/=5;c5--;}if(c2>c5)return c2>0 ? c2 : 0;elsereturn c5>0 ? c5 : 0;}void print(char c){if(ccnt==76){putchar('\n');ccnt=0;}putchar(c);++ccnt;}void print(int n){if (n>=10) print(n/10);print((char)('0'+(n%10)));}int main(){int n,d;freopen("fracdec.in","r",stdin);freopen("fracdec.out","w",stdout);scanf("%d%d",&n,&d);print(n/d);putchar('.');++ccnt;n%=d;int m=renum(n,d);for(int i=0;i<m;i++){n*=10;print(n/d);n%=d;}int r=n;if(r!=0){print('(');do{n*=10;print(n/d);n%=d;}while (n!=r);print(')');}putchar('\n');return 0;}

原创粉丝点击