ACM题解

将题解和题目集区分开主要是为了确保先思考,想方法,最后再对照题解
主要还是为了养成独立思考的好习惯

对应于习题集

https://weakdouqing.github.io/2019/05/22/%E9%A2%98%E7%9B%AE%E9%9B%86/

1.The Triangle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
题解:
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;

int a[101][101];
int dp[101][101];

int main()
{
int n, m;
int i, j;
while(scanf("%d",&m)!=EOF)
{

memset(dp,0,sizeof(dp));
for(i=1;i<=m;i++)
{
for(j=1;j<=i;j++)
{
scanf("%d",&a[i][j]);
}
}
for(j=1;j<=m;j++) dp[m][j] = a[m][j];
for(i=m-1;i>=1;i--)
{
for(j=1;j<=i;j++)
{
dp[i][j] = max(dp[i+1][j],dp[i+1][j+1]) + a[i][j];
}
}
cout<<dp[1][1]<<endl;
}

return 0;
}

2.区间完美数


1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<bits/stdc++.h>
using namespace std;
long long a,b,c,d;
long long lcm(long long a,long long b){
return a*b/__gcd(a,b);
}
long long solve(long long x){
return x-x/c-x/d+x/lcm(c,d);
}
int main(){
cin>>a>>b>>c>>d;
cout<<solve(b)-solve(a-1)<<endl;
return 0;
}

3.最短路

dijkstra算法写的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#define INF 0x3fffffff
using namespace std;
const int maxx=1e5;

int map[110][110], dis[110], vis[110];
void dijkstra(int n, int x)
{
int p, minn;
//将所有的两点间的距离存储,并将所有点设置为未访问
for(int i = 1; i <= n; i ++)
{
dis[i] = map[1][i];
vis[i] = 0;
}
vis[x] = 1;
//遍历所有点,找到最小路径
for(int i = 1; i <= n; i ++)
{
minn = INF;
for(int j = 1; j <= n; j ++)
{
if(!vis[j] && dis[j] < minn)
{
p = j;
minn = dis[j];
}
}
vis[p] = 1;
for(int j = 1; j <= n; j ++)
{
if(!vis[j] && dis[p] + map[p][j] < dis[j])
{
dis[j] = dis[p] + map[p][j];
}
}
}
}



int main()
{
int n, m, i, j, a, b, t;
//初始化距离值为无穷
while(scanf("%d %d", &n, &m)!=EOF)
{
if(n == 0 && m == 0) break;
for(i = 1; i <= n; i ++)
{
for(j = 1; j <= n; j ++)
{
map[i][j] = INF;
}
}
//设置两点之间的权值
for(i = 1; i <= m; i ++)
{
scanf("%d %d %d",&a, &b, &t);
map[a][b] = map[b][a] = t;
}
dijkstra(n, 1);
printf("%d\n",dis[n]);
}

return 0;
}

---------------- The End ----------------
0%