T639126 落落的去的数学问题
错误原因
#include<bits/stdc++.h>
using namespace std;
const int mod = 1e8;
long long n, a[300005], ans;
int main(){
cin >> n;
for(int i = 1; i <= n; i++){
cin >> a[i];
}
for(int i = 1; i <= n; i++){
for(int j = i + 1; j <= n; j++){
ans += (a[i] + a[j]) % mod;
}
}
cout << ans;
return 0;
}错误原因:暴力骗分。
正确代码
#include<bits/stdc++.h>
using namespace std;
const int mod = 1e8;
long long n, a[300005], ans, cnt;
int main(){
cin >> n;
for(int i = 1; i <= n; i++){
cin >> a[i];
}
sort(a + 1, a + n + 1);
for(int i = 1; i <= n; i++){
ans += a[i] * (n - 1);//求没有取模和去重后的总和。
cnt += n - (lower_bound(a + i + 1, a + n + 1, mod - a[i]) - a) + 1;//求重复算的数量。
}
cout << ans - cnt * mod;//总和减去重复的就等于答案。
return 0;
}总结:所有的减不符合的等于符合的。
T638485 第K小
错误代码
#include<bits/stdc++.h>
using namespace std;
long long n, k, a[15];
int main(){
cin >> n>> k;
for(int i = 1; i <= n; i++){
cin >> a[i];
}
sort(a + 1, a + n + 1);
if(a[k]){
cout << min(a[1] * k, a[k]);
}
else{
cout << a[1] * k;
}
return 0;
}错误原因:骗分代码。
正确代码
#include<bits/stdc++.h>
using namespace std;
long long n, k, a[15], cnt;
priority_queue<long long, vector<long long>, greater<long long> > q;//优先队列,自动从小到大排序。
map<long long, bool>mp;//去重
int main(){
cin >> n >> k;
for(int i = 1; i <= n; i++){
cin >> a[i];
if(mp[a[i]] == 0){//如果没有出现过就推入队列。
q.push(a[i]);
mp[a[i]] = 1;
}
}
while(!q.empty()){
long long sum = q.top();
cnt++;
q.pop();
if(cnt == k){//如果是第k小的数就直接输出。
cout << sum;
break;
}
for(int i = 1; i <= n; i++){
if(mp[a[i] + sum] == 0){//第cnt小的数加n中的数如果没有被标记过则推入队列。
q.push(a[i] + sum);
mp[a[i] + sum] = 1;
}
}
}
return 0;
}思路:模拟加贪心。
U591734 磁铁迷宫
错误思路
#include<bits/stdc++.h>
using namespace std;
int n, m;
char a[1005][1005];
int main(){
cin >> n >> m;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
cin >> a[i][j];
}
}
cout << 1;
return 0;
}错误原因:骗分代码。
正确代码
#include<bits/stdc++.h>
using namespace std;
const int dx[] = {0, 0, -1, 1};
const int dy[] = {-1, 1, 0, 0};
int n, m, a[1005][1005], ans = 1, t, vis[1005][1005], cnt;
char x;
void dfs(int x, int y){
for(int i = 0; i < 4; i++){
int xx = x + dx[i], yy = y + dy[i];
if(xx < 1 || xx > n || yy < 1 || yy > m || a[x][y] == 2 || vis[xx][yy] == t || a[xx][yy] == 1){//如果越界或前方不能走或是此格是磁铁旁边的格子,就跳过。
continue;
}
cnt++;//自由度加1。
vis[xx][yy] = t;
dfs(xx, yy);
}
}
int main(){
cin >> n >> m;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
cin >> x;
if(x == '#'){//如果是磁铁则此位置标记为1,四周标记为2。
a[i][j] = 1;
a[i + 1][j] = 2;
a[i][j + 1] = 2;
a[i - 1][j] = 2;
a[i][j - 1] = 2;
}
}
}
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
if(a[i][j] == 0 && !vis[i][j]){//如果没有被标记过则深搜。
cnt = 1;
vis[i][j] = ++t;
dfs(i, j);
ans = max(ans, cnt);//更新最大答案。
}
}
}
cout << ans;
return 0;
}总结:深搜加连通块。