P1518 [USACO2.4] 两只塔姆沃斯牛 The Tamworth Two
错误原因
循环次数判断错误,应该设置循环次数为极大值,我设置了100。
思路
模拟牛和这个人的行走路线即可,最多循环不会超过 100000 次,就算每个方格的每个方向都走过一遍也只有 次,然后有两个东西,就是 。
代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
char a[11][11];
int cx,cy,fx,fy;
int ct,ft;
int ans;
signed main(){
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
for(int i=1;i<=10;i++){
for(int j=1;j<=10;j++){
cin>>a[i][j];
if(a[i][j]=='C')cx=i,cy=j;
if(a[i][j]=='F')fx=i,fy=j;
}
}
int n=10,m=10;
while(!(cx==fx&&cy==fy)){
if(ct==0){
int xx=cx-1;
int yy=cy;
if(xx>=1&&xx<=n&&yy>=1&&yy<=m&&a[xx][yy]!='*'){
cx=xx;
cy=yy;
}else{
ct++;
ct%=4;
}
}else if(ct==1){
int xx=cx;
int yy=cy+1;
if(xx>=1&&xx<=n&&yy>=1&&yy<=m&&a[xx][yy]!='*'){
cx=xx;
cy=yy;
}else{
ct++;
ct%=4;
}
}else if(ct==2){
int xx=cx+1;
int yy=cy;
if(xx>=1&&xx<=n&&yy>=1&&yy<=m&&a[xx][yy]!='*'){
cx=xx;
cy=yy;
}else{
ct++;
ct%=4;
}
}else if(ct==3){
int xx=cx;
int yy=cy-1;
if(xx>=1&&xx<=n&&yy>=1&&yy<=m&&a[xx][yy]!='*'){
cx=xx;
cy=yy;
}else{
ct++;
ct%=4;
}
}
if(ft==0){
int xx=fx-1;
int yy=fy;
if(xx>=1&&xx<=n&&yy>=1&&yy<=m&&a[xx][yy]!='*'){
fx=xx;
fy=yy;
}else{
ft++;
ft%=4;
}
}else if(ft==1){
int xx=fx;
int yy=fy+1;
if(xx>=1&&xx<=n&&yy>=1&&yy<=m&&a[xx][yy]!='*'){
fx=xx;
fy=yy;
}else{
ft++;
ft%=4;
}
}else if(ft==2){
int xx=fx+1;
int yy=fy;
if(xx>=1&&xx<=n&&yy>=1&&yy<=m&&a[xx][yy]!='*'){
fx=xx;
fy=yy;
}else{
ft++;
ft%=4;
}
}else if(ft==3){
int xx=fx;
int yy=fy-1;
if(xx>=1&&xx<=n&&yy>=1&&yy<=m&&a[xx][yy]!='*'){
fx=xx;
fy=yy;
}else{
ft++;
ft%=4;
}
}
ans++;
if(ans>100001){
cout<<0;
return 0;
}
}
cout<<ans;
return 0;
}P3910 纪念邮票
错误原因
使用了双指针,两个指针分别对应他要买的邮票的那一段的左端点和右端点。
思路
枚举序列中的左端点,然后二分右端点,可以用等差数列求和。
可以推导公式,假设他要选区间长度为 ,化简之后确定 枚举这个 。
代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,m,sum;
signed main(){
cin>>n>>m;
m*=2;
for(int i=sqrt(m);i>0;i--){
if(m%i!=0)continue;
sum=m/i;
if((sum-i+1)%2==1||(sum+i-1)/2>n)continue;
cout<<'['<<(sum-i+1)/2<<','<<(sum+i-1)/2<<']'<<'\n';
}
return 0;
}P4047 [JSOI2010] 部落划分
错误原因
没写
思路
最小生成树每两个点之间建一条边,他要求求出最少的距离,就是最后一条有效边的长度。
代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,k;
double x[1005],y[1005];
struct node{
int u;
int v;
double w;
}e[1005*1005];
bool cmp(node a,node b){
return a.w<b.w;
}
int cnt;
int m;
int fa[1005];
int find(int x){
if(fa[x]==x)return x;
fa[x]=find(fa[x]);
return fa[x];
}
signed main(){
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
cin>>n>>k;
for(int i=1;i<=n;i++)fa[i]=i;
for(int i=1;i<=n;i++)cin>>x[i]>>y[i];
for(int i=1;i<=n;i++){
for(int j=i+1;j<=n;j++){
e[++m]={i,j,sqrt(pow(x[i]-x[j],2)+pow(y[i]-y[j],2))};
}
}
sort(e+1,e+1+m,cmp);
for(int i=1;i<=m;i++){
int x=find(e[i].u);
int y=find(e[i].v);
if(x!=y){
fa[x]=y;
cnt++;
if(cnt==n-k+1){
printf("%.2lf",e[i].w);
return 0;
}
}
}
return 0;
}